0Pricing
Swift Academy · 课时

约束(where)与类型推断

使用 where 约束泛型代码(例如 Equatable/Comparable 或 Element 约束),并了解 Swift 如何在调用处推断泛型类型。

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

为什么需要约束

添加约束,让泛型代码可以使用特定操作(例如 == 或 <)。随后,Swift 的类型推断会在调用时选择具体类型。

Equatable 约束

where T: Equatable 允许进行相等性检查。如果没有这个约束,任意 T 都不能使用 ==。

// Find the first index of value in an array of T
func indexOf<T>(_ value: T, in array: [T]) -> Int? where T: Equatable {
    for (i, x) in array.enumerated() {
        if x == value { return i }        // allowed because T: Equatable
    }
    return nil
}
print(indexOf(3, in: [1,2,3,2]) ?? -1)     // 2
print(indexOf("b", in: ["a","b","c"]) ?? -1)  // 1

Comparable 约束

使用类似 T: Comparable 的约束,可以启用 < 等排序操作。

// Return the minimum value of a collection when elements are Comparable
func minimum<T: Comparable>(_ xs: [T]) -> T? {
    guard var best = xs.first else { return nil }
    for x in xs.dropFirst() {
        if x < best { best = x }
    }
    return best
}
print(minimum([7,3,9]) ?? -1)    // 3
print(minimum(["b","a","c"]) ?? "?") // "a"

使用 where 的扩展

使用 where Element: ...,仅为特定元素类型添加 API(此处为满足 Equatable 的数组)。

// Add a helper only when the array's Element is Equatable
extension Array where Element: Equatable {
    func removingDuplicates() -> [Element] {
        var seen: [Element] = []
        for x in self {
            if !seen.contains(x) { seen.append(x) }
        }
        return seen
    }
}
print([1,2,2,3].removingDuplicates())   // [1,2,3]

多个约束

可以组合约束:同时约束泛型类型及其关联类型(例如 S.Element: Equatable)。

// Require both Sequence and Equatable elements; force same-type relationship
func allEqual<S>(_ s: S) -> Bool
where S: Sequence, S.Element: Equatable {
    var it = s.makeIterator()
    guard let first = it.next() else { return true }
    while let v = it.next() { if v != first { return false } }
    return true
}
print(allEqual([2,2,2]))   // true
print(allEqual([1,2,1]))   // false

实际使用中的类型推断

Swift 会根据参数和上下文推断泛型参数,因此很少需要显式指定 <T>。

// Inference: compiler deduces concrete types
let i = indexOf(10, in: [5,10,15])   // T is Int
let j = minimum(["z","x"])           // T is String
print(i ?? -1, j ?? "")

where 的含义

快速检查:where 子句的作用是什么?

回顾

回顾:使用 where 约束泛型(例如 T: Equatable、Element: Comparable),并依靠 Swift 的类型推断在调用时选择具体类型。

常见问题解答

「约束(where)与类型推断」课时是免费的吗?

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

「约束(where)与类型推断」这节课中我会学到什么?

使用 where 约束泛型代码(例如 Equatable/Comparable 或 Element 约束),并了解 Swift 如何在调用处推断泛型类型。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

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

「约束(where)与类型推断」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 泛型函数与类型
  2. 约束(where)与类型推断
  3. 集合上的泛型算法
← 返回 Swift Academy