swift的泛型貌似还差点意思

时间:2014-06-05 20:10:14   收藏:0   阅读:319
bubuko.com,布布扣
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()
    }
}
bubuko.com,布布扣

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

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

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

 

swift的泛型貌似还差点意思,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!