Swift 使用<>
来声明泛型函数或泛型类型:
1 func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
2 var result = ItemType[]()
3 for i in 0..times {
4 result += item
5 }
6 return result
7 }
8 repeat ("knock", 4)
Swift 也支持在类、枚举和结构中使用泛型:
1 // Reimplement the Swift standard library's optional type enum OptionalValue<T> {
2 case None
3 case Some (T)
4 }
5 var possibleInteger: OptionalValue<Int> = .None
6 possibleInteger = .Some (100)
有时需要对泛型做一些需求(requirements),比如需求某个泛型类型实现某个接口或继承自某个特定类型、两个泛型类型属于同一个类型等等,Swift 通过where
描述这些需求:
1 func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
2 for lhsItem in lhs {
3 for rhsItem in rhs {
4 if lhsItem == rhsItem {
5 return true
6 }
7 }
8 }
9 return false
10 }
11 anyCommonElements ([1, 2, 3], [3])