swift

Swift 5.x 关联类型

2020-07-10  本文已影响0人  ShenYj

关联类型的应用
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

个人理解: 感觉就是Swift在Protocol下定义泛型的一种语法标准, 如果按照struct的方式去定义protocol泛型, <T>这种写法会直接警报的

struct IntStack: Container {
    // original IntStack implementation
    var items = [Int]()
    mutating func push(_ item: Int) {
        items.append(item)
    }
    mutating func pop() -> Int {
        items.removeLast()
    }
    
    // conformance to the Container protocol
    typealias ItemType = Int
    mutating func append(_ item: Int) {
        self.push(item)
    }
    var count: Int {
        return items.count
    }
    subscript(i: Int) -> Int {
        return items[i]
    }
}

protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

泛型版本:

struct Stack<Element>: Container {
    // original IntStack implementation
    var items = [Element]()
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        items.removeLast()
    }
    
    // conformance to the Container protocol
    // Swift会自动推导出类型
    // typealias ItemType = Element 
    mutating func append(_ item: Element) {
        self.push(item)
    }
    var count: Int {
        return items.count
    }
    subscript(i: Int) -> Element {
        return items[i]
    }
}
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

关联类型的约束
protocol Container {
    // 要求其元素遵循Equatable协议
    associatedtype ItemType: Equatable
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}
protocol SuffixableContainer {
    associatedtype SuffixableContainer: SuffixableContainer where Suffix.Item == Item
    func suffix(_ size: Int) -> Suffix
}
上一篇下一篇

猜你喜欢

热点阅读