스위프트에서 where절은 특정 패턴과 결합하여 조건을 추가하는 역할을 합니다.
where 절은 크게 두 가지 용도로 사용됩니다.
- 패턴과 결합하여 조건 추가
- 타입에 대한 제약 추가
where 절의 다양한 예시를 살펴보겠습니다.
where 절을 사용하여 특정 조건을 만족하는 경우에만 패턴 매칭을 할 수 있습니다.
let number = 20
switch number {
case let x where x % 2 == 0:
print("\(x) is even")
case let x where x % 2 != 0:
print("\(x) is odd")
default:
print("Unknown number")
}
for-in 루프에서 where 절을 사용하여 특정 조건을 만족하는 요소만 반복할 수 있습니다.
let numbers = [1, 2, 3, 4, 5, 6]
for number in numbers where number % 2 == 0 {
print("\(number) is even")
}
// 출력: 2 is even, 4 is even, 6 is even
제네릭 함수나 타입에서 where 절을 사용하여 타입에 대한 추가적인 제약 조건을 정의할 수 있습니다.
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? where T: Comparable {
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
if let 또는 guard let 구문에서 where 절을 사용하여 추가적인 조건을 체크할 수 있습니다.
let optionalNumber: Int? = 42
if let number = optionalNumber, number > 40 {
print("The number is greater than 40: \(number)")
}
프로토콜에서 연관 타입에 대한 제약 조건을 정의할 때 사용할 수 있습니다.
protocol Container {
associatedtype Item
var items: [Item] { get }
func contains(_ item: Item) -> Bool where Item: Equatable
}
struct Box: Container {
var items: [String] = []
func contains(_ item: String) -> Bool where String: Equatable {
return items.contains(item)
}
}
이와 같이 where 절은 Swift에서 코드의 조건을 더 세밀하게 정의하고, 특정 상황에 맞게 필터링하거나 제약 조건을 설정하는 데 매우 유용합니다. 이를 통해 코드의 가독성과 유연성을 높일 수 있습니다. 조건 구문이나 논리 연산으로 구현한 코드보다는 훨씬 명확하고 간편하게 사용할 수 있기 때문에 코드의 가독성과 유연성을 높일 수 있습니다.