Protocol _012_swift protocol in the SWIFT standard library

Source: Internet
Author: User
Tags comparable hashable

//: 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.