Swift 中的泛型

  • 泛型函数的定义
  1. 泛型函数可以用于任何类型。
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}
  • 类型形式参数
  1. 上面的函数中,占位符类型 T 就是一个类型形式参数的例子。类型形式参数指定并且命名一个占位符类型,紧挨着卸载函数名后面的一对尖括号里(比如<T>)
  2. 一旦你指定了一个类型形式参数,你就可以用它定义一个函数形式参数
  3. 你可以通过在尖括号里写多个用逗号隔开的类型形式参数名,来提供更多类型形式参数。
  • 命名类型形式参数
  1. 大多数情况下,类型形式参数的名称都要有描述性,比如 Dictionary<Key, Value> 中的 Key 和 Value,借此告诉读者类型形式参数和泛型类型、泛型用到的函数之间的关系。但是,他们之间的关系没有意义时,一般按惯例用单个字母名字,比如 T U V
  2. 类型形式参数永远用大写开头的驼峰命名法命名,以致命他们是一个类型的占位符,不是一个值
  • 泛型类型
  1. 除了泛型函数,Swift 允许你定义自己的泛型类型。他们是可以用于任意类型的自定义类、结构体、枚举,和 Array、Dictionary 方法类似。
struct Stack<Element> {
    var items = [Element]()
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeLast()
    }
}
var stackOfStrings = Stack<String>()
stackOfStrings.push("one")
stackOfStrings.push("two")
stackOfStrings.push("three")
stackOfStrings.push("four")
  • 扩展泛型类型
  1. 当你扩展一个泛型类型时,不需要在扩展的定义中提供类型形式参数列表。原始类型定义的类型形式参数列表,在扩展提里仍然有效,并且原始类型形式参数列表名称也用于扩展类型形式参数。
extension Stack {
    var topItem: Element? {
        return items.isEmpty ? nil : items[items.count - 1]
    } 
}
  • 类型约束
  1. swapTwoValues(::) 函数和 Stack 类型可以用于任意类型。但是,有时在用于泛型函数的类型和泛型类型上,强制其遵循特定的类型约束很有用。类型约束支出一个类型形式参数必须继承自特定类,或者遵循一个特定的协议、组合协议。
  • 类型约束语法
  1. 在一个类型形式参数名称后面防止一个类或者协议作为形式参数列表的一部分,并用冒号隔开,以写出一个类型约束。
  2. Swift 标准库中定义了一个叫做 Equatable 的协议,要求遵循其协议的类型要实现操作符 (==) 和不相等操作符 (!=), 用于比较该类型的任意两个值。所有 Swift 标准库中的类型自动支持 Equatable 协议。
  3. 任何 Equatable 的类型都能安全地用于函数,因为可以保证哪些类型支持相等操作符。为了表达这个事实,当你定义函数时将 Equatable 类型约束作为类型形式参数定义的一部分书写;
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
    for (index, value) in array.enumerated() {
        if value == valueToFind {
            return index
        }
    }
    return nil
}
let names = ["one", "two", "three"]
print(findIndex(of: "two", in: names))

泛型的定义要求:where子句

  • where子句
  1. 如果类型约束中描述的一样,类型约束允许你在泛型类型相关的类型形式参数上定义要求。
  2. 类型约束在为关联类型定义要求时也很有用。通过定义一个泛型 where 子句来实现。泛型 where 子句让你能够要求一个关联类型必须遵循指定的协议,或者指定的类型形式参数和关联类型必须相同。泛型 where 子句以 where 关键字开头,后接关联类型的约束或类型和关联类型一致的关系。泛型 where 子句卸载一个类型或函数体的左半个大括号前面。
protocol Container {
    associatedtype ItemType//: Equatable
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}
func allItemsMath<C1: Container, C2: Container>(_ someContainer: C1, _ anotherContainer: C2) -> Bool where C1.ItemType == C2.ItemType, C1.ItemType: Equatable {
    if someContainer.count != anotherContainer.count {
        return false
    }
    for index in 0..<someContainer.count {
        if someContainer[index] != anotherContainer[index] {
            return false
        }
    }
    return true
}
  • 带有泛型 where 子句的扩展
  1. 你同时也可以使用泛型的 where 子句来作为扩展的一部分
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

struct Stack<Element>: Container {
    var items = [Element]()
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeLast()
    }

    mutating func append(_ item: Element) {
        self.push(item)
    }
    var count: Int {
        return items.count
    }
    subscript(i: Int) -> Element {
        return items[i]
    }
}
extension Stack where Element: Equatable {
    func isTop(_ item: Element) -> Bool {
        guard let topItem = items.last else {
            return false
        }
        return topItem == item
    }
}
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}
extension Container where ItemType: Equatable {
    func startsWith(_ item: ItemType) -> Bool {
        return count >= 1 && self[0] == item
    }
}
extension Container where ItemType == Double {
    func average() -> Double {
        var sum = 0.0
        for index in 0..<count {
            sum += self[index]
        }
        return sum / Double(count)
    }
}

关联类型的泛型 where 子句
你可以在关联类型中包含一个泛型 where 子句。比如说:假定你想要做一个包含遍历器的 Container,比如标准库中 Sequence 协议那样

protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
    
    associatedtype Iterator: IteratorProtocol where Iterator.Element == ItemType
    func makeIterator() -> Iterator
}

protocol ComparableContainer: Container where ItemType: Comparable { }

泛型下标

  1. 下标可以使泛型,他们可以包含泛型 where 子句。你可以在 subscript 后用尖括号来写类型占位符,你还可以在下标代码块花括号前些泛型 where 分句。
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get } 
}

extension Container {
    subscript<Indices: Sequence>(indices: Indices) -> [ItemType] where Indices.Iterator.Element == Int {
        var result = [ItemType]()
        for index in indices {
            result.append(self[index])
        }
        return result
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift泛型介绍 泛型是为Swift编程灵活性的一种语法,在函数、枚举、结构体、类中都得到充分的应用,它的引入可...
    Bobby0322阅读 14,194评论 0 26
  • 什么时候需要使用泛型 在讲到泛型之前,先写一段代码(文中的代码都是Swift书写)。 这是一个很常见的也很简单的I...
    BennyLoo阅读 3,080评论 1 4
  • 1. 泛型函数 T 是占位类型名,用来代替实际类型名。 2. 泛型类型 下面的例子定义了一个泛型的栈(stack)...
    keisme阅读 427评论 0 0
  • 时隔1个月,2个月,3个月。。。我终于回来了。。公司项目太忙了以至于简书一直没有更新。而且公司项目还是OC的。。最...
    MelodyZhy阅读 1,534评论 1 5
  • 作者:Thomas Hanning,原文链接,原文日期:2015/09/09译者:pmst;校对:numbbbbb...
    梁杰_numbbbbb阅读 447评论 0 4