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") } } // 扩展协议 CustomStringConvertible extension 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 HighSchoolStudent extension Student where Self:HighSchoolStudent { func showInfo() { print("name is" + " \(name)" + " " + "height is" + " \(height)" + " " + "age is " + "\(age)") } } // 扩展协议 CustomStringConvertible extension 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