where

木木木大约 1 分钟iOSSwift语法

where

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

for循环中的使用

使用for-loop打印偶数:

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
}

协议扩展中的使用

基于其元素扩展Array类型:

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

first元素筛选的使用

根据条件获取第一个元素:

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

contains筛选的使用

确定数组是否包含条件匹配元素:

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

初始化中的使用

条件初始化器仅允许某些类型初始化:

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"
上次编辑于:
贡献者: perhapsdone