Skip to content

Swift 入门(15):泛型

泛型(Generics)让你编写 可复用、灵活、安全 的代码。
通过占位符 T 表示任意类型,避免重复写同样的函数或类。

1. 泛型函数

swift
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

var x = 5, y = 10
swapTwoValues(&x, &y)
print(x, y) // 10 5

var s1 = "hello", s2 = "world"
swapTwoValues(&s1, &s2)
print(s1, s2) // world hello

2. 泛型类型(结构体 / 类)

swift
struct Stack<T> {
    private var items: [T] = []

    mutating func push(_ item: T) {
        items.append(item)
    }

    mutating func pop() -> T? {
        return items.popLast()
    }
}

var intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
print(intStack.pop()!) // 2

3. 类型约束

有时需要限定泛型类型必须遵循某个协议。

swift
func findIndex<T: Equatable>(of value: T, in array: [T]) -> Int? {
    for (index, item) in array.enumerated() {
        if item == value { return index }
    }
    return nil
}

print(findIndex(of: "b", in: ["a", "b", "c"])) // 1

4. 关联类型(协议里的泛型)

swift
protocol Container {
    associatedtype Item
    mutating func add(_ item: Item)
    var count: Int { get }
}

struct IntContainer: Container {
    var items: [Int] = []
    mutating func add(_ item: Int) { items.append(item) }
    var count: Int { items.count }
}

总结

  • 泛型函数:func foo<T>(...) {}
  • 泛型类型:struct Stack<T> {...}
  • 类型约束:<T: Equatable>
  • 协议可用 associatedtype 声明泛型。

本站总访问