在尖括号里写一个名字来创建一个泛型函数或者类型。
- 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)
在类型名后面使用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])
练习:修改anyCommonElements函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。
简单起见,你可以忽略where,只在冒号后面写接口或者类名。<T: Equatable>和<T where T: Equatable>是等价的。