欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swift泛型的一些理解

程序员文章站 2022-03-12 23:00:55
...
protocol MyProtocol {
    //关联类型
    associatedtype ItemType
    mutating func append(_ item:ItemType)
    mutating func getObj(_ index:Int) -> ItemType
    //下标
    subscript(i:Int) -> ItemType{ get }
    var count: Int { get }
}

struct MyDataSturce<T>:MyProtocol {
    var count: Int {
        return items.count
    }
    subscript(i: Int) -> (T) {
        return items[i];
    }

    var items = [T]();
    mutating func getObj(_ index: Int) -> T {
        return items[index];
    }

    mutating func append(_ item: T) {
        items.append(item)
    }
}

struct MyDataSturce1<T>:MyProtocol {
    var items = [T]()
    
    subscript(i: Int) -> T {
        return items[i]
    }

    mutating func getObj(_ index: Int) -> T {
        return items[index]
    }

    mutating func append(_ item: T) {
        items.append(item)
    }

    var count: Int {
        return items.count
    }
}

//结构体stack使用泛型T作为占位符
struct Stack<T> {
    var items = [T]()
    mutating func push(_ item:T){
        items.append(item)
    }
    func pop() -> T {
        return items.last!
    }
    //查找目标在数组中的index  泛型S满足Equatable协议
    static func findIndex<S:Equatable>(ofString valueToFind:S,in array:[S]) -> Int?{
        for (index,value) in array.enumerated() {
            if value == valueToFind {
                return index;
            }
        }
        return nil;
    }
    //匹配两个数组是否相等 两个数组满足MyProtocol协议 并且两个ItemType相等 并且ItemType满足Equatable协议
    static func allMatch<C1:MyProtocol,C2:MyProtocol>(_ array1:C1,_ array2:C2) -> Bool where C1.ItemType == C2.ItemType,C1.ItemType:Equatable{
        if array1.count != array2.count {
            return false
        }
        for i in 0..<array1.count {
            if array1[i] != array2[i] {
                return false
            }
        }
        return true
    }
}
extension Stack{
    func topItem() -> T? {
        return items.isEmpty ? nil : items[items.count - 1];
    }
}
//扩展Stack 使用泛型满足Equatable这个协议
extension Stack where T:Equatable{
    func isTop(_ item:T) -> Bool {
        guard let topItem = items.last else {
            return false
        }
        return item == topItem
    }
}
//扩展MyProtocol协议 使ItemType满足Equatable协议
extension MyProtocol where ItemType:Equatable{
    func startWith(_ item:ItemType) -> Bool {
        return count >= 1 && self[0] == item;
    }
}
//扩展MyProtocol协议 使ItemType满足为Int类型
extension MyProtocol where ItemType == Int{
    var sum: Int {
        var ss = 0
        for i in 0..<count {
            ss = self[i] + ss
        }
        return ss
    }
}