码迷,mamicode.com
首页 > 编程语言 > 详细

Swift标准库中的协议_012_swift协议

时间:2016-06-08 12:09:36      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Swift标准库中的协议_012_swift协议

标签:

原文地址:http://www.cnblogs.com/foreveriOS/p/5569544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!