공부/SWIFT

[SWIFT] 제어문(조건문 if , switch)

알로하리미 2021. 3. 10. 10:56
728x90

스위프트의 흐름 제어 구문에서는 소괄호()를 대부분 생략 가능

중괄호{}는 생략 불가

 

1. 조건문

1.1 if문

if 구문의 조건의 값이 꼭 Bool 타입이여야 합니다.

temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's really warm. Don't forget to wear sunscreen."

 

 

1.2 switch 구문

break 키워드는 선택 사항이다. 안써도되고 가시성을 위해 써도 좋다.
다른 언어는 break를 사용하지 아니하면 아래 케이스까지 실행되었지만 스위프트는 아니다.
비교될 값이 명확히 한정적인값이 아닐 때는 default 를 꼭 작성해야한다.

 

case연속 실행하려면 fallthrough 키워드를 사용

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."

 

 

범위 연산자 사용이 가능하다

let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// Prints "There are dozens of moons orbiting Saturn."

 

case안에 하나의 실행 구문이 꼭 있어야한다.

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, case문에 body가 없으므로 에러가 발생합니다.
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// 컴파일 에러 발생!

 

case안에 , 로 복수의 조건을 설정 할 수 있다.

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// Prints "The letter A"

 

튜플을 조건으로 사용할 수 있다. 와일드카드( _ ) 사용 가능 (무엇이 와도 좋다는 뜻)

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"

 

값을 바인딩 할 수 있다.( 들어오는값과의 연결 )

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"

 

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"

 

열거형에 대해서 switch문을 작성시 모든 case를 작성해주면 오류가 나지 않는다. 미래에 기존열거형이 추가 되어서 모든 case에 대해서 처리를 깜박하였을때 오류를 알려줄 속성이 unknown 속성이다. 그 오류경고를 보고 개발자가 새로이 case를 추가해주면 된다. ( 처리 안해줬을때 오류 내용 : Switch must be exhaustive )

enum Menu {
    case chicken
    case pizza
    case hamburber
}

let lunchMenu: Menu = .chicken

switch lunchMenu {
    case .chicken:
        print("chicken")
    case .pizza:
        print("pizza")
    @unknown case _: //case _ == case default랑 똑같은 기능이다.  무조건 마지막에 코딩
        print("what?")
}

 

아래 url을 통해 제어 전송 구문을 확인 할 수 있다. break, continue, fallthrough

2021.03.10 - [분류 전체보기] - [SWIFT] 제어 전송 구문