本节书摘来自异步社区《Swift开发实战》一书中的第2章,第2.8节泛型,作者 李宁,更多章节内容可以访问云栖社区“异步社区”公众号查看
2.8 泛型在Swift语言中,在尖括号里写一个名字来创建一个泛型函数或者类型。例如,如下所示的演示代码。
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] { var result = ItemType[]() for i in 0..times { result += item } return result } repeat("knock", 4) 你也可以创建泛型类、枚举和结构体。 // Reimplement the Swift standard library's optional type enum OptionalValue<T> { case None case Some(T) } var possibleInteger: OptionalValue<Int> = .None possibleInteger = .Some(100)在Swift语言中,在类型名后面使用where关键字来指定对类型的需求。例如,限定某个类型来实现某一个协议,限定两个类型是相同的,或者限定某个类必须有一个特定的父类。例如,如下所示的演示代码。
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1, 2, 3], [3])在Swift语言中,可以忽略where关键字,只在冒号后面写协议或者类名。例如,如下两种格式是完全等价的。
<T: Equatable> <T where T: Equatable> 相关资源:敏捷开发V1.0.pptx