咱们还是先上代码吧
protocol Human { var name:String{ get set } var isMan:Bool{set get} class var isUsable:Bool { set get } //类成员,表示这个类是否可用 func ageDescription(ages:Int...) //函数参数可以是变长参数 } class Student{ var name = "" } class PrimaryStudent:Student,Human{ class var isUsable:Bool{ get{ return self.isUsable } set{ self.isUsable = newValue } } var isMan:Bool init(name:String,isMan:Bool){ self.isMan = isMan super.init() self.name = name } func ageDescription(ages:Int...){ var ageCount = 0 for age in ages{ ageCount += age; } println("this man age is \(ageCount)") } }
protocol RandomNumberGenerator { func random() -> Double } class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } class LinearCongruentialGenerator: RandomNumberGenerator { func random() -> Double { return random()%10.0 } } var d6 = Dice(sides: 6,generator: LinearCongruentialGenerator())
protocol NameComplete { func nameSetCompleted(theName:String) } class Student{ var delegate:NameComplete? var name:String{ didSet{ self.delegate?.nameSetCompleted(name) } } init(name:String,delegate:NameComplete){ self.name = name self.delegate = delegate } } class DoSth:NameComplete{ func nameSetCompleted(theName:String){ println("name:\(theName) is set ") } } var a = DoSth() var b = Student(name:"",delegate:a) b.name = "小笨狼" //输出:name:小笨狼 is set
@objc protocol Human{ @optional var name:String{get set} @optional func descript() } class Student:Human{ var name:String = "abc" func descript(){ println("abc") } }
protocol pName{ var name:String{set get} } protocol dName:pName{ func descript() } class Human:dName{ var name = "" func descript(){ println(name) } }
protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person: Named, Aged { var name: String var age: Int } func wishHappyBirthday(celebrator: protocol<Named, Aged>) { println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!") } let birthdayPerson = Person(name: "Malcolm", age: 21) wishHappyBirthday(birthdayPerson) //输出Happy birthday Malcolm - you're 21!
原文:http://blog.csdn.net/xbenlang/article/details/32717651