什么是Swift的关联类型(associated type)

474 阅读1分钟

Swift的关联类型(associated type)基本是和协议一起使用的。直接解释这个概念有可能会让你迷糊,直接上代码倒是好很多。

什么是关联类型

关联类型是在定义协议的时候某个类型的占位类型。在协议被用于某个特定类型的时候,这个占位类型会被具体的某个类型代替。如:

protocol StringsCollection {
    var count: Int { get }
    subscript(index: Int) -> String { get }
    mutating func append(_ item: String)
} 

如果你希望Double类型的集合也可以用同样的逻辑,你就不得不定义一个新的协议。关联类型正好可以避免这个问题,如:

protocol Collection {
    associatedtype Item
    var count: Int { get }
    subscript(index: Int) -> Item { get }
    mutating func append(_ item: Item)
}

关联类型使用关键字associatedtype定义。在Collection协议里,subscript返回的和append方法添加的都是同一个类型。

在使用上面定义的Collection协议的时候:

struct UppercaseStringsCollection: Collection {

  var container: [String] = []
  var count: Int { container.count }

  mutating func append(_ item: String) {
    guard !container.contains(item) else { return }
    container.append(item.uppercased())
  }

  subscript(index: Int) -> String {
    return container[index]
  }
}

有了关联类型,让服用逻辑变得更加简单,有效的避免写多余的代码。