泛型类型约束
//泛型类型约束
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
for (index, value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
print(findIndex(of: "abc", in: ["a", "b", "c", "abc"]))
//Optional(3)
关联类型:协议使用泛型
//关联类型:协议使用泛型
protocol Container {
associatedtype ItemType: Equatable
mutating func append(_ item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct IntStack: Container {
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
//指定类型
typealias ItemType = Int
mutating func append(_ item: Int) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Int {
return items[i]
}
}
泛型结构体使用泛型协议
泛型结构体使用泛型协议,不需要用 typealias 指定类型,可以推断出来
//泛型结构体使用泛型协议,不需要用 typealias 指定类型,可以推断出来
struct Stack<Element: Equatable>: 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]
}
}
var stack = Stack<String>()
stack.push("abc")
print(stack.count)
//1
泛型 where 子句
//泛型 where 子句
func allItemMatch<C1: Container, C2: Container>(_ someContainer: C1, _ anotherContainer: C2) -> Bool where C1.ItemType == C2.ItemType {
if someContainer.count != anotherContainer.count {
return false
}
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
return true
}
where扩展泛型
//where扩展泛型
extension Stack where Element: Comparable {
}
关联类型的泛型 where 子句
//关联类型的泛型 where 子句
protocol ContainerTwo {
associatedtype ItemType: Equatable
mutating func append(_ item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
associatedtype Iterator: IteratorProtocol where Iterator.Element == ItemType
func makeIterator() -> Iterator
}
扩展泛型下标
//扩展泛型下标
extension ContainerTwo {
subscript<Indices: Sequence>(indices: Indices) -> [ItemType] where Indices.Iterator.Element == Int {
var result = [ItemType]()
for index in indices {
result.append(self[index])
}
return result
}
}