Swift 공식 문서 The Basics를 바탕으로 정리합니다!
: an alternative name for an existing type
Type aliases are useful when you want to refer to an existing type by a name that’s contextually more appropriate, such as when working with data of a specific size from an external source
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min // maxAmplitudeFound is now 0
: Tuples group multiple values into a single compound value.
같은 타입이 아니여도 튜플형태로 묶을 수 있다.
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)") // Prints "The status code is 404"
print("The status message is \(statusMessage)") // Prints "The status message is Not Found"
print("The status code is \(http404Error.0)") // Prints "The status code is 404"
print("The status message is \(http404Error.1)") // Prints "The status message is Not Found"
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)") // Prints "The status code is 200"
print("The status message is \(http200Status.description)") // Prints "The status message is OK"
: 값이 있을 수도 있고 없을 수도 있는 상황에 사용합니다
Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.
can’t use nil with non-optional constants and variables.
If you define an optional variable without providing a default value, the variable is automatically set to nil for you
You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=).
if let constantName = someOptional {
statements
}
func canThrowAnError() throws {
// this function may or may not throw an error
}
do {
try canThrowAnError()
// no error was thrown
} catch {
// an error was thrown
}
: 런타임 시 발생하는 것들을 확인. Assertion은 개발과정에서 실수를 잡고 preconditions는 문제를 감지하는 데 도움을 줍니다.
assertion 또는 precondition 의 조건이 true 면 코드는 계속 실행되고 false 면 현재 프로그램 상태가 invalid 하다고 판단되어서 코드 실행이 멈추고 앱이 종료된다!
let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 is not >= 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.")
}
: precondition은 조건이 거짓이 될 가능성이 있지만 코드가 실행되기 위해선 반드시 참이어야 할 때 사용합니다.
// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")