[swift] 03. 제어문
for
// Dictionary key value
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
switch
- Switch case 안에 콤마(,)로 구분해서 복수의 case 조건을 혼합(compound)해 사용
- 튜플을 조건으로 사용
let somePoint = (1, 1) switch somePoint { case (0, 0): print("\(somePoint) is at the origin") case (_, 0): print("\(somePoint) is on the x-axis") case (0, _): print("\(somePoint) is on the y-axis") case (-2...2, -2...2): print("\(somePoint) is inside the box") default: print("\(somePoint) is outside of the box") } // Prints "(1, 1) is inside the box"
- 값 바인딩 (Value Bindings)
let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): print("on the x-axis with an x value of \(x)") case (0, let y): print("on the y-axis with a y value of \(y)") case let (x, y): print("somewhere else at (\(x), \(y))") } // Prints "on the x-axis with an x value of 2"
- case 에 where 사용
let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: print("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: print("(\(x), \(y)) is on the line x == -y") case let (x, y): print("(\(x), \(y)) is just some arbitrary point") } // Prints "(1, -1) is on the line x == -y"
- 혼합 케이스, 값-바인딩
let stillAnotherPoint = (9, 0) switch stillAnotherPoint { case (let distance, 0), (0, let distance): print("On an axis, \(distance) from the origin") default: print("Not on an axis") } // Prints "On an axis, 9 from the origin"
- fallthrough. 다음 case를 진행
let integerToDescribe = 5 var description = "The number \(integerToDescribe) is" switch integerToDescribe { case 2, 3, 5, 7, 11, 13, 17, 19: description += " a prime number, and also" fallthrough default: description += " an integer." } print(description) // Prints "The number 5 is a prime number, and also an integer."
Label
label 이름과 while 조건을 넣어 특정 구문을 실행하는 구문으로 사용 label name: while condition { statements }
guard
특정 조건을 만족하지 않으면 이 후 코드를 실행하지 않도록 방어코드를 작성 ```swift func greet(person: [String: String]) { guard let name = person[“name”] else { return }
print(“Hello (name)!”)
guard let location = person[“location”] else { print(“I hope the weather is nice near you.”) return }
print(“I hope the weather is nice in (location).”) }
greet(person: [“name”: “John”]) // Prints “Hello John!” // Prints “I hope the weather is nice near you.” greet(person: [“name”: “Jane”, “location”: “Cupertino”]) // Prints “Hello Jane!” // Prints “I hope the weather is nice in Cupertino.”
### 버전 확인
```swift
if #available(iOS 10, macOS 10.12, *) {
// Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
// Fall back to earlier iOS and macOS APIs
}