Swift Academy · 课时

函数上的 where 子句

为泛型函数添加细粒度约束。

第 2 / 4 课13 个步骤

函数上的 where 子句 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。

超越简单约束

像 <T: Collection> 这样的约束描述的是 T 本身。但有时您需要约束 T 的关联类型,例如它的 Element。这正是 where 子句的作用。

func sumInts<C: Collection>(_ c: C) -> Int where C.Element == Int {
    c.reduce(0, +)
}
print(sumInts([1, 2, 3]))

同类型要求

where C.Element == Int 要求集合的元素必须恰好是 Int,从而可以执行针对整数的操作。

func describe<C: Collection>(_ c: C) -> String where C.Element == Int {
    "Sum is " + String(c.reduce(0, +))
}
print(describe(Set([1, 2, 3])))

对元素的协议要求

您可以要求元素遵循某个协议,而不是要求它必须是某一种确切类型,这样更加灵活。

func joinAll<C: Collection>(_ c: C) -> String
    where C.Element: CustomStringConvertible {
    c.map { $0.description }.joined(separator: ", ")
}
print(joinAll([1, 2, 3]))

where 位于签名之后

where 子句位于返回类型和函数体之间。<> 内的约束与 where 子句中的约束会共同发挥作用。

func maxElement<C: Collection>(_ c: C) -> C.Element?
    where C.Element: Comparable {
    c.max()
}
print(maxElement([4, 9, 2])!)

关联两个类型参数

where 子句可以使用 == 将两个不同泛型的元素类型关联起来。

func combine<A: Collection, B: Collection>(_ a: A, _ b: B) -> [A.Element]
    where A.Element == B.Element {
    Array(a) + Array(b)
}
print(combine([1, 2], Set([3])))

多个 where 条件

请列出多个要求,并用逗号分隔,以表达组合约束。

func report<C: Collection>(_ c: C)
    where C.Element: Comparable, C.Element: CustomStringConvertible {
    if let m = c.max() { print("max:", m.description) }
}
report([5, 1, 9])

约束嵌套的关联类型

在处理嵌套集合时,您还可以进一步深入约束,例如要求某个元素的元素满足特定条件。

func flatten<C: Collection>(_ c: C) -> [Int]
    where C.Element: Collection, C.Element.Element == Int {
    c.flatMap { Array($0) }
}
print(flatten([[1, 2], [3]]))

包含 Equatable 元素的 where 约束

要求元素遵循 Equatable,就可以搜索泛型集合。

func indexOf<C: Collection>(_ x: C.Element, in c: C) -> C.Index?
    where C.Element: Equatable {
    c.firstIndex(of: x)
}
if let i = indexOf(2, in: [1, 2, 3]) { print("found") }

带 where 的泛型方法

泛型类型中的方法也可以使用 where,通常用于仅针对特定元素类型添加行为。

struct Wrap<T> {
    let items: [T]
    func total() -> Int where T == Int { items.reduce(0, +) }
}
print(Wrap(items: [1, 2, 3]).total())

提高可读性

与把复杂约束全部塞进尖括号相比,将它们写在 where 子句中更清晰;当存在多个关联类型条件时尤其如此。

func first<C: Collection>(_ c: C) -> String
    where C.Element: CustomStringConvertible {
    c.first.map { $0.description } ?? "empty"
}
print(first([10, 20]))

标准库中的 where

序列的序列上的 joined() 等方法,会在内部使用 where 子句来精确表达其要求。

let nested = [[1, 2], [3, 4]]
print(Array(nested.joined()))

快速检查

请检查您对函数 where 子句的理解。

回顾

where 子句可以约束泛型的关联类型:要求元素是某个特定类型(== Int)、遵循某个协议(: Comparable)、关联两个参数的元素,或深入嵌套的关联类型。它们位于签名之后,并能让复杂约束更易读。

免费开始

用 AI 导师学习 Swift — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
122
课程
409

常见问题解答

「函数上的 where 子句」课时是免费的吗?

是的 — 「函数上的 where 子句」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。

「函数上的 where 子句」这节课中我会学到什么?

为泛型函数添加细粒度约束。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「函数上的 where 子句」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Swift Academy 课中编写并运行代码吗?

能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 类型参数约束
  2. 函数上的 where 子句
  3. 约束关联类型
  4. 泛型下标与扩展
← 返回 Swift Academy