The Swift Programming Language学习笔记

来源:互联网 发布:linux执行了bin文件 编辑:程序博客网 时间:2024/05/18 19:22
//泛型函数func swapTwoValues<T>(_ a: inout T, _ b: inout T) {    let temporaryA = a    a = b    b = temporaryA}
// 泛型类型struct Stack<Element> {    var items = [Element]()    mutating func push(_ item: Element) {        items.append(item)    }    mutating func pop() -> Element {        return items.removeLast()    }}
// 泛型类型拓展extension Stack {    var topItem: Element? {        return items.isEmpty ? nil : items.last    }}
// 类型参数约束class SomeClass {}protocol SomeProtocol {}func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {}
// 关联类型(也可以约束)protocol Container {    associatedtype Item // 可以: Equatable等    mutating func append(_ item: Item)    var count: Int { get }    subscript(i: Int) -> Item { get }}// Type inference可以推断出Container协议中的Item类型为Elementstruct Stack<Element>: 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]    }}
// 泛型where从句func allItemsMatch<C1: Container, C2: Container>    (_ someContainer: C1, _ anotherContainer: C2) -> Bool    where C1.Item == C2.Item, C1.Item: Equatable {     if someContainer.count != anotherContainer.count {         return false     }     for i in 0..<someContainer.count {         if someContainer[i] != anotherContainer[i] {             return false         }     }     return true }
// 泛型where从句拓展类型、协议extension Stack where Element: Equatable {    func isTop(_ item: Element) -> Bool {        guard let topItem = items.last else {            return false        }        return topItem == item    }}extension Container where Item: Equatable {    func startsWith(_ item: Item) -> Bool {        return count >= 1&& self[0] == item    }}// 也可指定关联类型为具体类型extension Container where Item == Double {    func average() -> Double {        var sum = 0.0        for index in 0..<count {            sum += self[index]        }        return sum / Double(count)    }}
// 泛型where从句在关联类型应用protocol Container {    associatedtype Item    mutating func append(_ item: Item)    var count: Int { get }     subscript(i: Int) -> Item { get }    associatedtype Iterator: IteratorProtocol where Iterator.Element == Item    func makeIterator() -> Iterator}
// 协议继承时用泛型where从句约束继承的关联类型protocol ComparableContainer: Container where Item: Comparable {}
// 泛型下标extension Container {    subscript<Indices: Sequence>(indices: Indices) -> [Item]        where Indices.Iterator.Element == Int {            var result = [Item]()            for index in indices {                result.append(self[index])            }            return result    }}
原创粉丝点击