본문 바로가기
Swift

알쓸스잡 - 6

by songmoro 2025. 1. 21.
728x90

stride

  • stride(from: , to: , by:)
    • 열린 범위 -> 0...5
  • stride(from: , through: , by:)
    • 닫힌 범위 -> 0..<4

 

switch 연속 케이스

  • fallthrough를 사용하면 C 처럼 케이스 이후 다음 케이스로 넘어감
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."

 

defer 수행 순서

  • 첫 defer 블럭이 가장 마지막에 수행 됨
if score < 10 {
    defer {
        print(score)
    }
    defer {
        print("The score is:")
    }
    score += 5
}
// Prints "The score is:"
// Prints "6"

 

API 확인

  • 특정 타겟에서 사용 가능한지 SDK를 통해 확인
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
}

 

  • 어노테이션
@available(macOS 10.12, *)
struct ColorPreference {
    var bestColor = "blue"
}

 

  • guard
func chooseBestColor() -> String {
    guard #available(macOS 10.12, *) else {
        return "gray"
    }
    let colors = ColorPreference()
    return colors.bestColor
}

 

 

  • 사용 불가능 검사
if #unavailable(iOS 10) {
    // Fallback code
}

 

참고

https://bbiguduk.github.io/swift-book-korean/documentation/the-swift-programming-language-korean/controlflow
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow

728x90

'Swift' 카테고리의 다른 글

알쓸스잡 - 8  (0) 2025.02.02
알쓸스잡 - 7  (0) 2025.02.01
알쓸스잡 - 5  (0) 2025.01.17
알쓸스잡 - 4  (0) 2024.12.30
알쓸스잡 - 3  (0) 2024.12.30