/* The generic function 1:equatable increases the filtering for whether = = and! = are supported. Get a class test first ~ 2: operator overloaded functions have to write outside. 3: Inherit from NSObject do not write protocol equatable, unclear reason ~*/func swapvalue<t:equatable> (inout left:t,inout right:t), Void {let B UF = left left = right right = Buf}var Aleft = 3;var aright = 5SwapValue (&aleft, right: &aright) print ("Aleft : \ (aleft); Aright:\ (aright) ") class swapclass:equatable{var id = 5 init (aid:int) {id = aid}}func = = (l:swapclass,r:s Wapclass), 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 (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 ()!) /* Generic constraint was previously written. Now copy it again. 1: There is no previous container agreement, here is not clear, because before what kind of, I do not know ~ 2:_arraytype cannot be replaced with CollectionType protocol, because count returns a value type */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! = AnotherContai Ner.count {return false} for I in 0..<anothercontainer.count {if anothercontainer[i]! = Somecont ainer[i]{return False}} return true; Print ([Allitemsmatchnew], Anothercontainer: [1,2,3,5])? " Same ":" Different ")/*stack template Class 1: After inheriting from NSObject, can use mytemplatebase<int> to do the type of accurate judgment. 2: The template declaration is clearly more straightforward than C + +, and there is a constraint syntax. Very good ~ */class mytemplatebase<templatename>:nsobject{private var myData = [templatename] () func Pop () Temp Latename {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")}
Reference: Http://www.swiftvip.cn/guide/chapter2/23_Generics.html#extending_a_generic_type
[Swift Learning eight] generics exercise