[swift学习之八]泛型练习

/*泛型函数
 1:Equatable增加对是否支持==和!=的过滤。弄个类试验先~
 2:运算符重载函数得写外面。
 3:继承自nsobject就不用写协议Equatable了,不清楚原因~
*/
func SwapValue<T:Equatable>(inout left:T,inout right:T) -> Void {
    let Buf = left
    left = right
    right = Buf
}
var ALeft = 3;var ARight = 5
SwapValue(&ALeft, right: &ARight)
print("Aleft:\(ALeft);ARight:\(ARight)")

class SwapClass:Equatable{
    var ID = 5
    init(aid:Int){
        ID = aid
    }
}
func == (l:SwapClass,r:SwapClass) -> Bool {
    return l.ID == r.ID
}
var Al = SwapClass(aid: 4)
var Ar = SwapClass(aid: 8)
SwapValue(&Al, right: &Ar)
print("AClassleft:\(Al.ID)")
print("AClassRight:\(Ar.ID)")

/*栈(Stack)
*/
struct Stack<T> {
    private var items = [T]()
    mutating func Push(Item:T)->T{
        items.append(Item)
        return Item
    }
    mutating func Pop()->T{
       return items.removeLast()
    }
}
extension Stack
{
    func TopItem() -> T? {
        return self.items.isEmpty ? nil : self.items.last
    }
    var count :Int{
        return items.count
    }
}
var s1 = Stack<Int>()
s1.Push(5)
s1.Push(6)
print(s1.TopItem()!)

/*泛型约束
 以前写过了。现在再复制一遍。
 1:没有以前的Container协议了,这里还没弄清楚,因为以前什么样,我也不知道~
 2:_ArrayType不能用CollectionType协议替代,原因是count返回值类型
 */
func allItemsMatchNew<C1, C2
    where C1:_ArrayType, C2:_ArrayType,
    C1.Generator.Element:Equatable,
    C1.Generator.Element == C2.Generator.Element>
    (someContainer: C1, anotherContainer: C2) -> Bool {
    if someContainer.count != anotherContainer.count {
        return false
    }
    for i in 0..<anotherContainer.count {
        if anotherContainer[i] != someContainer[i]{
            return false
        }
    }
    return true;
}
print(allItemsMatchNew([1,2,3], anotherContainer: [1,2,3,5]) ?"相同" :"不同")

/*Stack模版类
 1:继承于NSObject后,能用MyTemplateBase<Int>做类型的准确判断。
 2:模版的声明明显比c++要简单明了,而且还有约束的语法。挺好的~
 */
class MyTemplateBase<TemplateName>:NSObject{
   private var myData = [TemplateName]()
    func Pop() -> TemplateName {
        return myData.removeLast()
    }
    func Push(Item:TemplateName) -> TemplateName {
        self.myData.append(Item)
        return Item
    }
    func count() -> Int {
      return self.myData.count
    }
    func Description() -> Void {
        print(self.myData)
    }
}
let S2 = MyTemplateBase<Int>()
S2.Push(5)
S2.Push(8)
S2.Description()
if S2.isKindOfClass(MyTemplateBase<Int>) {
    print("S2 is MyTemplateBase")
}
参考:http://www.swiftvip.cn/guide/chapter2/23_Generics.html#extending_a_generic_type

你可能感兴趣的:(泛型,swift)