标签:
//: Playground - noun: a place where people can play import UIKit //--Swift标准库中的协议---// //1.实例的比较:判断两个实例值是否相同 let a = 4, b = 4 a == b //(Int类型的比较) //自定义结构体类型,进行是否相等的比较 struct Games { var winCount : Int var loseCount : Int } let g1 = Games(winCount: 2, loseCount: 1) let g2 = Games(winCount: 2, loseCount: 1) //g1 == g2 //自定义类型判断是否相等需要遵守协议Equatable extension Games : Equatable {} //==为方法名,因为此协议方法是通过==来调用 func ==(g1 : Games, g2 : Games) -> Bool { return g1.winCount == g2.winCount && g1.loseCount == g2.loseCount } if g1 == g2 { print("相同") } else { print("不同") } //2.比较两个实例的大小 Comparable extension Games : Comparable {} //协议方法实现的逻辑由编程者自己定义,要符合常规的逻辑 func <(g1 : Games, g2 : Games) -> Bool { let gScore1 = g1.winCount - g1.loseCount let gScore2 = g2.winCount - g2.loseCount return gScore1 < gScore2 } g1 < g2 //3.哈希协议 class Student { var ID : Int? var name : String? init(ID: Int, name:String) { self.ID = ID self.name = name } } extension Student : Hashable { //扩展计算属性hashValue var hashValue : Int { return ID! } } //Hashable继承自Equatable协议,因此必须实现==协议方法 func ==(s1 : Student, s2 : Student) -> Bool { return s1.ID == s2.ID } var s1 = Student(ID: 1000, name: "kathy") var s2 = Student(ID: 1001, name: "Tom") let stuSet : Set<Student> = [s1, s2, s2, s2] stuSet.count let stuDic : [Student : String] = [s1 : "Class 1", s2 : "Class 2"] stuDic.count
标签:
原文地址:http://www.cnblogs.com/foreveriOS/p/5569544.html