swift 协议泛型associatedtype

协议 中不支持<T>这中方式写泛型

需要使用associatedtype关键字

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

 可以实现协议看下具体如何使用

//: FROM  https://www.anuomob.com

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

struct InStack: Container{
    var count: Int
        var items=[Int]()
    mutating func append(_ item: Int) {
        items.append(item)
    }
    

    
    subscript(i: Int) -> Int {
        return items[i]
    }
    

    
    typealias ItemType = Int
    

    
    //自定义方法
    mutating func pop()->Int{
        return items.removeLast()
    }
    
}

同时也可以添加约束

    associatedtype ItemType:Equatable
//协议可作为它自身的要求出现
protocol SuffixableContainer:Container{
    associatedtype Item:Equatable
    associatedtype Suffix: SuffixableContainer where Suffix.Item == ItemType
    func suffix(_ size:Int)->Suffix
}

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/108312270