翻译:where在Swift中的用法

说明

Swift中强大的关键字where可以轻松过滤出值。它可以用于许多不同的变体中,本文中列出了其中的大多数变体。

enum中的用法

考虑具有以下枚举:

enum Action {
    case createUser(age: Int)
    case createPost
    case logout
}

使用,where您可以轻松过滤特定年龄范围的案件:

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循环打印偶数。

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
}

extension协议扩展中的用法

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

参考

https://www.avanderlee.com/swift/where-using-swift/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值