//: Playground-noun:a Place where people can playImport UIKit//protocol---in the--swift standard library////1. Example comparison: Determine whether two instance values are the sameLet A =4, B =4a= = B//(comparison of type int)//custom struct type, compare for equalitystructGames {var wincount:int var losecount:int}let G1= Games (Wincount:2, Losecount:1) Let G2= Games (Wincount:2, Losecount:1)//G1 = = G2//custom types Determine whether equality is required to comply with the protocol equatableextension games:equatable {}//= = is the method name, because this protocol method is called by = =Func = = (G1:games, g2:games)Bool {returnG1.wincount = = G2.wincount && G1.losecount = =G2.losecount}ifG1 = =G2 {print ("same")} Else{print ("different")}//2. Compare the size of two instances comparableextension games:comparable {}//the logic of the implementation of the Protocol method is defined by the programmer itself, to conform to the general logicFunc < (g1:games, G2:games)Bool {Let gScore1= G1.wincount-G1.losecount let GScore2= G2.wincount-G2.losecountreturnGScore1 <GSCORE2}G1<G2//3. Hash protocolclassStudent {var id:int?var name:string?Init (Id:int, name:string) {self.id=ID Self.name=name}} Extension student:hashable {//extended Computed Properties HashValuevar hashvalue:int {returnId! } }//Hashable inherits from the Equatable protocol, so the = = Protocol method must be implementedFunc = = (S1:student, s2:student)Bool {returnS1.id = =s2.id}var S1= Student (ID: +, Name:"Kathy") var s2= Student (ID:1001, Name:"Tom") Let Stuset:set<Student> =[S1, S2, S2, s2]stuset.countlet studic: [student:string]= [S1:"Class 1", S2:"Class 2"]studic.count
Protocol _012_swift protocol in the SWIFT standard library