struct Size: Equatable,Comparable,customstringconvertible { // 相等的协议 var wIDth: Double var height: Double var description: String { return "witth:" + "\(self.wIDth)" + " " + "height" + "\(self.height)" }}// 相等协议的实现func ==(left: Size,right: Size) -> Bool { return left.height == right.height && left.wIDth == right.height}// 比较协议的实现func <(left: Size,right: Size) ->Bool { if left.wIDth * left.height != right.height * right.wIDth { return left.wIDth * left.height < right.height * right.wIDth } return left.wIDth * left.height > right.height * right.wIDth}
扩展协议
protocol student:customstringconvertible { var name: String{get} var height: Double {get} }// 扩展协议,在协议扩展中可以添加具体的逻辑extension student { var description: String { return "name is" + " \(name)" + " " + "height is" + " \(height)" } func showInfo() { print("good student") }}// 扩展协议 customstringconvertibleextension customstringconvertible { var descriptionWithDate:String { return NSDate().description + " " + description }}class Person: student { var name: String = "" var height: Double = 0.0 init(name: String,height: Double) { self.name = name self.height = height }}var person = Person(name: "jobs",height: 1.80)print(person)person.showInfo()print(person.descriptionWithDate)
name is jobs height is 1.8
good student
2017-02-24 08:57:15 +0000 name is jobs height is 1.8
对已有的协议修改
protocol Student: customstringconvertible { var name: String{get} var height: Double {get} }// 扩展协议,在协议扩展中可以添加具体的逻辑extension Student { var description: String { return "name is" + " \(name)" + " " + "height is" + " \(height)" } func showInfo() { print("good student") }}protocol HighSchoolStudent { var age: Int {get}}// 对已有的协议做修改 当类准守HighSchoolStudent的协议时 打印 good HighSchoolStudentextension Student where Self:HighSchoolStudent { func showInfo() { print("name is" + " \(name)" + " " + "height is" + " \(height)" + " " + "age is " + "\(age)") }}// 扩展协议 customstringconvertibleextension customstringconvertible { var descriptionWithDate:String { return NSDate().description + " " + description }}class Person: Student { var name: String = "" var height: Double = 0.0 init(name: String,height: Double) { self.name = name self.height = height }}class People: Student,HighSchoolStudent { internal var height: Double = 0.0 internal var name: String = "" internal var age: Int = 0 init(height:Double,name: String,age: Int) { self.name = name self.age = age self.height = height }}var person = Person(name: "jobs",height: 1.80)print(person)person.showInfo()print(person.descriptionWithDate)var people = People(height: 1.7,name: "zhangsan",age: 17)people.showInfo()
上面代码打印结果:
name is jobs height is 1.8
good student
2017-02-24 09:44:12 +0000 name is jobs height is 1.8
name is zhangsan height is 1.7 age is 17
总结以上是内存溢出为你收集整理的Swift 常用标准库协议全部内容,希望文章能够帮你解决Swift 常用标准库协议所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)