관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift 공식 문서] 5. Control flow (흐름 제어) 본문

swift 공식 문서

[iOS - swift 공식 문서] 5. Control flow (흐름 제어)

jake-kim 2021. 6. 21. 23:53

For - in 루프

  • stride(from:to:by:)
  • stride(from:through:by:): through 포함

While 루프

  • repeat - while: 조건을 고려하기 전 repeat블록을 부조건 한번 실행
repeat {
    
} while <condition>

조건문

  • switch 문의 암시적 fall through
    • case문을 여러개 사용하지 않고, 컴마로 구분하여 'or 조건' 사용
      (주의: if문에서는 콤마가 'end 조건')

let anotherCharacter: Character = "a"

// 컴파일 에러
switch anotherCharacter {
case "a":
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}

// 정상 동작
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}
  • switch 문의 명시적 fall through
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)
  • switch의 case에 범위 사용
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).")
  • switch문에 tuple 사용
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"
  • binding기능: case에 let으로 선언할 경우, 값 binding
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"

API 버전 가용성

  • if #available 사용
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
}

 

Comments