泛型
泛型是 Swift
最强大的特性之一,很多 Swift
标准库是基于泛型代码构建的。简单理解,就是一个泛化
的类型,并不特指某一个具体的类型。
泛型
的使用:
作为函数的参数或返回值
一旦函数内部确定了T
的具体类型,那么所有的T
都是改类型func swapTwoValues<T>(_ a: inout T, _ b: inout T) { // 一旦函数内部确定了 T 的具体类型,那么所有的 T 都是改类型 let temporaryA = a a = b b = temporaryA }
泛型与类型的结合
1、与结构体的结合:
struct Point<T> { var x: T var y: T } let p1 = Point(x: 1, y: 1) let p2 = Point(x: 1.1, y: 1.1)
2、 与类的结合
class Stack<T> { var array: [T] = [] func pop() -> T? { return array.removeLast() } func push(_ value: T) { array.append(value) } } let s1 = Stack<Any>() s1.push(1) s1.push("string") s1.pop() s1.pop()
3、与协议的关联
protocol WorkProtocol { // 使用关键字 'associatedtype' associatedtype T func run() -> T func eat() -> T } class Person: WorkProtocol { func run() -> Person { return self } func eat() -> Person { return self } } class Dog: WorkProtocol { func run() -> Dog { return self } func eat() -> Dog { return self } } let p1 = Person() p1.run().eat().run().eat() let d1 = Dog() d1.eat().run().eat().run()
泛型与where字句的结合使用
func test<T>(a: T) where T: Person { } test(a: p1) test(a: d1) // 会报错