翻译:where在Swift中的用法

翻译: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/

Read more

🚀Zeek.ai一款基于 Electron 和 Vite 打造的跨平台(支持 Windows、macOS 和 Linux) AI 浏览器

🚀Zeek.ai一款基于 Electron 和 Vite 打造的跨平台(支持 Windows、macOS 和 Linux) AI 浏览器

是一款基于 Electron 和 Vite 打造的跨平台(支持 Windows、macOS 和 Linux) AI 浏览器。 集成了 SearXNG AI 搜索、开发工具集合、 市面上最流行的 AI 工具门户,以及代码编写和桌面快捷工具等功能, 通过模块化的 Monorepo 架构,提供轻量级、可扩展且高效的桌面体验, 助力 AI 驱动的日常工作流程。

By Ne0inhk
超快速,使用ChatGPT编写回归和分类算法

超快速,使用ChatGPT编写回归和分类算法

本文将使用一些 ChatGPT 提示,这些提示对于数据科学家在工作时非常重要。 微信搜索关注《Python学研大本营》,加入读者群,分享更多精彩 以下是一些示例ChatGPT 提示的列表以及数据科学家的响应。 ChatGPT 提示 为决策树回归算法生成 python 代码。 下面是使用scikit-learn在 Python 中进行决策树回归的示例代码: import numpy as np import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeRegressor # Generate random data rng = np.random.default_rng() x = 5 * rng.random(100) y = np.sin(x) + 0.

By Ne0inhk
力扣每日一题:993.二叉树的堂兄弟节点 深度优先算法

力扣每日一题:993.二叉树的堂兄弟节点 深度优先算法

993.二叉树的堂兄弟节点 难度:简单 题目: 在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。 如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点。 我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 x 和 y 。 只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false。 示例: 示例 1: 输入:root = [1,2,3,4], x = 4, y = 3 输出:false

By Ne0inhk