본문 바로가기
Swift

Swift where syntax

by HaningYa 2020. 10. 27.
728x90

SwiftUI에서 재사용 가능한 view 를 만드는 부분에서 이런 문법이 나왔다.

struct GridView<Content>: View where Content: View {
...

 

where 이 추가적인 조건을 주는건 어렴풋이 알고있는데 저렇게 View where Content : View 로 프로토콜에 쓰이는 건 처음봐서 where 절이 쓰일 수 있는 경우를 정리해본다.

where 는 값들을 filter 할 수 있는 강력한 기능이고 다양하게 쓰일 수 있다.

Switch 문에서의 사용

enum Action {
    case createUser(age: Int)
    case createPost
    case logout
}
func printAction(action: Action) {
    switch action {
    case .createUser(let age) where age < 21:
        print("Young and wild!")
    case .createUser:
        print("Older and wise!")
    case .createPost:
        print("Creating a post")
    case .logout:
        print("Logout")
    }
}

printAction(action: Action.createUser(age: 18)) // Young and wild
printAction(action: Action.createUser(age: 25)) // Older and wise

 

첫번째 case 인 .createUser 에서 where 절로 추가적으로 age < 21 이라는 조건을 달아줬다.

*여기서 enum 에서 case 가 값을 가지는데 이것은 Associated Values 라고 한다.


Associated Values

it’s sometimes useful to be able to store values of other types alongside these case values.
This additional information is called an 
associated value, and it varies each time you use that case as a value in your code.
[docs.swift.org/swift-book/LanguageGuide/Enumerations.html]


for 반복문에서 사용

let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for number in numbers where number % 2 == 0 {
    print(number) // 0, 2, 4, 6, 8, 10
}

말 그대로 짝수만 출력한다.

protocol extensions 에서의 사용

extension Array where Element == Int {
    func printAverageAge() {
        let total = reduce(0, +)
        let average = total / count
        print("Average age is \(average)")
    }
}

let ages = [20, 26, 40, 60, 84]
ages.printAverageAge() // Average age is 46

Array type 을 extending 하는데 일반적인 Array type이 아닌 Array type 중에서도 Element 가 Int 인 type 만을 extension

Usage in first

let names = ["Henk", "John", "Jack"]
let firstJname = names.first(where: { (name) -> Bool in
    return name.first == "J"
}) // Returns John

Usage in contains

let fruits = ["Banana", "Apple", "Kiwi"]
let containsBanana = fruits.contains(where: { (fruit) in
    return fruit == "Banana"
}) // Returns true

Usage in initializer

extension String {
    init(collection: T) where T.Element == String {
        self = collection.joined(separator: ",")
    }
}

let clubs = String(collection: ["AJAX", "Barcelona", "PSG"])
print(clubs) // prints "AJAX, Barcelona, PSG"

이제 다시 코드를 보면

struct GridView<Content>: View where Content: View {
...

GridView 라는 구조체는 재사용 가능한 SwiftUI view인데

GridView 는 View 라는 SwiftUI 프로토콜을 준수하며 

GridView<Content> 로 받아오는 Content type 또한 View 프로토콜을 준수해야 한다

라는 의미이다.


[코드출처]

 

Where usage in Swift - SwiftLee

Where is a powerful keyword within Swift to filter out values. It can be used in many different variants from which most of them are listed in this post.

www.avanderlee.com

 

728x90

'Swift' 카테고리의 다른 글

Swift Closure (일급객체 함수)  (0) 2021.03.25
Swift High Order Function Summary  (0) 2020.10.06
[DI] Initializer로 Swift 의존성 주입하기  (0) 2020.09.03
ARC - Automatic Reference Counting  (0) 2020.08.24
Swift: 프로퍼티와 메서드  (0) 2020.07.13

댓글