여러 값을 튜플 하나에 담아 확인할 수도 있다. 언더스코어 _
를 통해서는 어떤 값이라도 매칭되도록 만들 수도 있다.
let point = (1, 2)
switch point {
case (0, 0):
print("origin")
case (_, 0):
print("x-axis")
case (0, _):
print("y-axis")
case (-2...2, -2...2):
print("inside the box: size of 2 by 2")
default:
print("outside the box")
}
// inside the box: size of 2 by 2
// (0, 0) matched only in the first case (0, 0), not other cases like (_, 0)
임시 변수/상수에 이름을 붙일 수도 있다.
let point = (2, 0)
switch point {
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 an y value of \(y)")
case let (x, y):
print("somewhere at \(x) and \(y)")
}
// on the x-axis with an x value of 2
switch 조건 안에서 앞서 사용한 변수/상수에 이름을 붙여 활용하자.
where
을 통해 추가적인 조건을 달 수 있다.
let point = (1, -1)
switch point {
case let (x, y) where x == y:
print("on the line y = x")
case let (x, y) where x == -y:
print("on the line y = -x")
case let (x, y):
print("on point \(x) and \(y)")
}
컴마 ,
를 통해 조건과 case
이 일치되는 부분을, value binding에서 특정 패턴과 매칭이 일어나는지 확인할 수 있다.
let alphabet: Character = "e"
switch alphabet{
case "a", "e", "i", "o", "u":
print("vowel")
default:
print("not vowel")
}
let point = (7, 0)
switch point{
case (let distance, 0), (0 let distance):
print("on an axis \(distance) from the origin")
default:
print("not on an axis")
}
코드 블록이 실행되었을 때 컨트롤을 변경할 수 있는 방법이 있다.
반복문 내에서 실행 중인 코드를 멈추고 다시 다음 반복할 부분의 시작을 실행하라는 문법이다.
let phrase = "Hello, Swift!"
let vowels: [Character] = ["a", "e", "i", "o", "u"]
for letter in phrase{
if !vowels.contains(letter){
continue
}
print("\(letter)")
}
// e
// o
// i
특정 조건이 만족되었을 때 이 반복문 안에서 탈출할 수 있다.
반복문 안에서 break
를 사용하면 곧바로 코드 블록 바깥으로 컨트롤이 옮겨진다.
switch
문을 사용할 때 특정 조건이 일어나는 상황에서 아무런 동작도 하지 않으려면 break
를 통해 곧바로 switch
문 자체를 탈출한다.
C와 같이 break
를 사용하지 않을 때 이후 case
의 블록을 연달아 실행하고 싶다면 fallthrough
를 사용할 수 있다.
let num = 5
var msg = "The number \(num) is"
swtich num {
case 2, 3, 5, 7, 11, 13, 17, 19:
msg += " a prime and"
fallthrough
default:
msg += " an integer."
}
print(msg)
// The number 5 is a prime and an integer.
여러 개의 조건문을 사용할 때 이 블록에 이름을 붙여 구분할 수 있다.
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
gameLoop: while square != finalSquare {
diceRoll += 1
if diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// diceRoll will move us to the final square, so the game is over
break gameLoop
case let newSquare where newSquare > finalSquare:
// diceRoll will move us beyond the final square, so roll again
continue gameLoop
default:
// this is a valid move, so find out its effect
square += diceRoll
square += board[square]
}
}
print("Game over!")
guard
문은 불리언 값에 따라 코드를 실행할지를 결정한다. 이 guard
문 다음에 오는 코드는 무조건적으로 참이어야 한다. if
와는 다르게 else
를 무조건적으로 사용해야 한다.
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."
위 greet
함수는 person
이라는 딕셔너리를 파라미터로 받는다. location
이 있다면 이 지역 문자열을 사용한 문구를 출력하는데, 이때 guard
와 else
를 통해 참 여부를 확실하게 확인할 수 있다.
스위프트는 맥과 아이폰 버전에 적용 가능한 API를 확인할 수 있는 #available
를 지원한다.
if #available(iOS 10, macOS 10.12, *){
// iOS 10 and macOS 10.12 APIs
} else {
// earlier iOS and macOS
}
if
문 안의 블록은 주어진 파라미터 이상 기기에서 실행하도록 만든다. 이때 watchOS
, tvOS
등 다른 파라미터 역시 설정할 수 있다.