swift泛型下标
原创
©著作权归作者所有:来自51CTO博客作者mp624183768的原创作品,请联系作者获取转载授权,否则将追究法律责任
//: FROM https://www.anuomob.com
import UIKit
protocol Container{
associatedtype Item
mutating func append(_ item:Item)
var count:Int{get}
subscript(i:Int)->Item {get}
}
extension Container{
subscript<Indices:Sequence>(indices:Indices)->[Item] where Indices.Iterator.Element == Int{
var result=[Item]()
for index in indices{
result.append(self[index])
}
return result
}
}
class IntStack: Container{
var items = [Int]()
subscript(i: Int) -> Int {
return items[i]
}
func append(_ item: Int) {
items.append(item)
}
var count: Int {
return items.count
}
typealias Item = Int
}
var intStack = IntStack()
intStack.append(1)
intStack.append(2)
print(intStack[[0,1]])
结果
[1, 2]