-
Swift 정리 #1 기본코딩/Swift 2022. 12. 9. 15:33728x90
이 정리글들은 Swift 프로그래밍을 설명하는 것이 아닌, 기본적인 예들을 읽으며 궁금할 때 찾아보려고 정리한 것들이다.
상세한 해설은 아래 링크를 통해 볼 수 있다.기본
Comments
// Comments /* Multi line comments /* nested comments */ */
Constants & Variable(상수와 변수)
let myConstant = 10 // 상수 var myVar = 20 // 변수 var a = 1, b = 2, c = 3 // 여러 변수 한 줄에 쓰기 var myString: String = "Hello" // 변수형 선언 var d, e, f: Double // 여러 변수에 변수형 선언 let ☢︎ = "Warning" // 변수이름에 유니코드 등도 사용 가능, 단 숫자나 화이트스페이스는 불가 var `let` = "keyword" // 키워드를 변수이름으로 사용하려면 backtick(`) 사용
; 여러 문장을 한 줄에 쓰기
let world = "world"; print(world)
데이터형식
숫자
Integer(정수)
숫자의 종류: signed(+, -, 0), unsigned(+, 0)
8, 16, 32, 64 bit- Int, Int32, Int64 (pc에 따라, 32bit는 32, 64는 64bit)
- UInt : unsigned int
let minInt8 = Int8.min, maxInt8 = Int8.max
Double & Float
Double: 64 bit, Float: 32 bit
let myDouble: Double = 32.0 // double let myFloat: Float = 16.0 // float
Numeric literals(숫자 표현)
let decimalInteger = 17 let binaryInteger = 0b10001 // 17 in binary notation let octalInteger = 0o21 // 17 in octal notation let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 // decimal exp: e let hexadecimalDouble = 0xC.3p0 // hexadecimal exp: p
let paddedDouble = 000123.456 // padding 000 let oneMillion = 1_000_000 // padding _ let justOverOneMillion = 1_000_000.000_000_1
숫자데이터타입 변경
let a: UInt16 = 2_000 let b: UInt8 = 1 let c = a + UInt16(b) // UInt16(): integer conversion
let a = 3 let b = 0.14159 let c = Double(a) + b // Integer and Floating-Point Conversion
Type inference(데이터타입 예측)
let myInt = 32 // Int let pi = 3.14 // Double
Type aliase
typealias myNumber = UInt16 var myVar = myNumber.min
Boolean
let TrueIsTrue = true let FalseIsFalse = false if TrueIsTrue { print("True") } else { print("False") }
Tuples
tuple: data set
let http404Error = (404, "Not Found") // tuple let (statusCode, statusMessage) = http404Error // decompose print("The status code is \(statusCode)") print("The status message is \(statusMessage)") let (justTheStatusCode, _) = http404Error // ignore _ parts print("The status code is \(justTheStatusCode)") print("The status code is \(http404Error.0)") // index 0,1.. print("The status message is \(http404Error.1)") let http200Status = (statusCode: 200, description: "OK") // naming print("The status code is \(http200Status.statusCode)") print("The status message is \(http200Status.description)")
Optionals(?)
변수의 값이 없을 수도 있는 경우 사용
let Number = "123" // Int?(optional int) let IntNumber = Int(Number)
nil
var OptInt: Int? = 100 OptInt = nil var NoValue: String? // NoValue is automatically set to nil
// If문: 값의 유무 확인 if IntNumber != nil { print("IntNumber contains some value.") } if IntNumber != nil { print("IntNumber has a value of \(IntNumber!).") }
Optional binding
if let constantName = someOptional { statement }
if let aNumber = Int(bNumber) { print("The string \"\(bNumber)\" has a value of \(aNumber)") } else { print("The string \"\(bNumber)\" couldn't be converted to an integer") }
let myNumber = Int(aNumber) if let myNumber = myNumber { print("My number is \(myNumber)" }
if let myNumber { print("My number is \(myNumber)") }
if let Number_1 = Int("5"), let Number_2 = Int("50"), Number_1 < Number_2 && Number_2 < 100 { print("\(Number_1) < \(Number_2) < 100") } // same function if let Number_1 = Int("5") { if let Number_2 = Int("50") { if Number_1 < Number_2 && Number_2 < 100 { print("\(Number_1) < \(Number_2) < 100") } } }
암묵적인 optional unwrapping
let possibleString: String? = "An optional string." let forcedString: String = possibleString! // requires an exclamation point let assumedString: String! = "An implicitly unwrapped optional string." let implicitString: String = assumedString // no need for an exclamation point let optionalString = assumedString // The type of optionalString is "String?" and assumedString isn't force-unwrapped. if assumedString != nil { print(assumedString!) } // Prints "An implicitly unwrapped optional string." if let definiteString = assumedString { print(definiteString) } // Prints "An implicitly unwrapped optional string."
Error handling
func canThrowAnError() throws { // this function may or may not throw an error } do { try canThrowAnError() // no error was thrown } catch { // an error was thrown }
func makeASandwich() throws { // ... } do { try makeASandwich() eatASandwich() } catch SandwichError.outOfCleanDishes { washDishes() } catch SandwichError.missingIngredients(let ingredients) { buyGroceries(ingredients) }
Assertions and Preconditions
Debugging with Assertions
let age = -3 assert(age >= 0, "A person's age can't be less than zero.") // This assertion fails because -3 isn't >= 0.
assert(age >= 0)
if age > 10 { print("You can ride the roller-coaster or the ferris wheel.") } else if age >= 0 { print("You can ride the ferris wheel.") } else { assertionFailure("A person's age can't be less than zero.") }
Enforcing Preconditions
// In the implementation of a subscript... precondition(index > 0, "Index must be greater than zero.")
728x90'코딩 > Swift' 카테고리의 다른 글
Swift 정리 #6 함수 (0) 2022.12.14 Swift 정리 #5 Control flow (1) 2022.12.14 Swift 정리 #4 컬렉션 타입 (0) 2022.12.14 Swift 정리 #3 문자열과 문자 (0) 2022.12.13 Swift 정리 #2 연산자 (0) 2022.12.13