首页 > 代码库 > swift的泛型貌似还差点意思

swift的泛型貌似还差点意思

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

}

// Container<T> ???
// protocol not gen!
struct Hole<T>: Container {
    typealias ItemType = T
    var elements = ItemType[]()
    var count: Int {
    get{
        return elements.count
    }
    }
    mutating func append(item: ItemType){
        elements.append(item)
    }
    subscript(i: Int) -> ItemType {
        return elements[i]
    }
    mutating func removelast() -> ItemType{
        return elements.removeLast()
    }
}

class Stack<T>{
    var storage = Hole<T>()
    typealias ItemType = T
    typealias StorageType = Hole<T>.ItemType
    func push(item:ItemType) {
        storage.append(item)
    }
    func pop() -> ItemType{
        return storage.removelast()
    }
}

protocol不支持泛型,带来很多限制,不够灵活, 难道是为了兼容objc?

如果可以这么用,就会更灵活

class Stack<T, T2:Container>{
    var storage = T2<T>()
    ....
}