var x = 0.0, y = 0.0, z = 0.0
var welcomeMessage: String
var red, green, blue: Double
var `class`: String = "aa";
print(`class`)
// This is a comment.
/* This is also a comment
but is written over multiple lines. */
/* This is the start of the first multiline comment.
/* This is the second, nested multiline comment. */
This is the end of the first multiline comment. */
let cat = "aaa"; print(cat)
let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8
리터럴 : 소스코드에 무슨 값인지 보이는거
let meaningOfLife = 42
let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double
숫자 표현 (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
없음 → 10진법 0b ~ → 2진법 0o ~ → 8진법 0x ~ → 16진법Floating-Point
Exponential
기타 가독성을 위한 특수문법
zero padding / 언더바
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
SomeType(ofInitialValue)
를 사용하면 "넣어주는 value"로 해당 Type의 initializer가 수행되며 새로운 인스턴스를 생성한다let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
let integerPi = Int(pi)
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
let i = 1
if i {
// 컴파일 에러
}
사용예시 - 선언
let http404Error = (404, "Not Found")
사용예시 - 값 추출
//값 추출 #1
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
print("The status message is \(statusMessage)")
//값 추출 #2
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
//값 추출 #3
print("The status code is \(http404Error.0)")
print("The status message is \(http404Error.1)")
사용예시 - Name을 부여할 수도 있다
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
print("The status message is \(http200Status.description)")
정수 initializer 중 String → Int 변환자는 실패할 수 있으므로 optional을 return하도록 선언되어 있다
if convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber!).")
}
if let actualNumber = Int(possibleNumber) {
print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
print("The string \"\(possibleNumber)\" couldn't be converted to an integer")
}
if let 구문의 의미는,
"Int(possibleNumber)에서 return되는 Optional Int 타입의 value가 존재하면 이를 unwrapping하여 actualNumber에 저장한다"
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
//일반 Optional
let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation point
//암시적 Unwrapped Optionals
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation point
let assumedString: String! = "An implicitly unwrapped optional string."
//optionalString의 타입은 "String?"가 된다
let optionalString = assumedString
//기본은 일반 Optional로 간주되므로 if let구문에도 사용가능
if let definiteString = assumedString {
print(definiteString)
}
Error를 던지는 함수임을 알림 - throws
Error가 발생할 수 있는 코드영역 - do
Error를 던지는(throw) 함수 - try
Error 발생 시 수행할 코드 - catch
func canThrowAnError() throws {
// this function may or may not throw an error
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
//parameter(ex. ingredients)를 넣어주면 error의 내용이 담긴다
Assertions and Preconditions
디버깅 목적으로 runtime 중에 어떤 확인 작업을 넣는 것
어떤 코드를 실행하기 전에 반드시 만족해야 하는 조건에 "예기치 않은" 문제가 있는지 확인절차를 넣을 수 있다.
명백히 일어나면 안되는 조건을 넣는 것이므로 복구같은 것 없이 app을 종료시킨다. 에러에 대한 예방책으로 동작하는게 아니다
이런 구문은 documentation 기능을 할 수도 있다
Assertions과 Preconditions의 차이는
Assertion은 Debug build에서만 동작
Precondition은 Debug + Product build 모두에서 동작
그러므로, 개발 중엔 Assertion을 막 써도 된다
// assert(_:_:file:line:)
let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
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 {
//이미 fail인게 확인되었으면 조건문없이 바로 assert
assertionFailure("A person's age can't be less than zero.")
}
App을 종료시켜버리기 때문에 명백히 잘못일때만 사용할 것
// precondition(_:_:file:line:)
precondition(index > 0, "Index must be greater than zero.")
//이미 fail인게 확인되었으면 조건문없이 바로 precondition
preconditionFailure("Index must be greater than zero.")