protocol ExampleProtocol{
var simpleDescription:String{get}
mutating func adjust()
}
class SimpleClass:ExampleProtocol{
var simpleDescription:String = "A very simple class"
var anotherProperty:Int = 69105
func adjust(){
simpleDescription += " Now 100% requested"
}
}
var a = SimpleClass()
print(a.simpleDescription)
a.adjust()
print(a.simpleDescription)
******************************************
protocol tcpprotocol {
init(aprot: Int)
}
class tcpClass: tcpprotocol {
required init(aprot: Int) {
}
}
// 使用required修饰符可以保证:所有的遵循该协议的子类,同样能为构造器规定提供一个显式的实现或继承实现。
// 如果一个子类重写了父类的指定构造器,并且该构造器遵循了某个协议的规定,那么该构造器的实现需要被同时标示required和override修饰符:
protocol tcpprotocol {
init(no1: Int)
}
class mainClass {
var no1: Int // 局部变量
init(no1: Int) {
self.no1 = no1 // 初始化
}
}
class subClass: mainClass, tcpprotocol {
var no2: Int
init(no1: Int, no2 : Int) {
self.no2 = no2
super.init(no1:no1)
}
// 因为遵循协议,需要加上"required"; 因为继承自父类,需要加上"override"
required override convenience init(no1: Int) {
self.init(no1:no1, no2:0)
}
}
let res = mainClass(no1: 20)
let show = subClass(no1: 30, no2: 50)
print("res is: (res.no1)")
print("res is: (show.no1)")
print("res is: (show.no2)")
******************************************
struct SimpleStructure:ExampleProtocol{
var simpleDescription:String = "A simple structure"
mutating func adjust(){
simpleDescription += " (adjust)"
}
}
var b = SimpleStructure()
print(b.simpleDescription)
b.adjust()
print(b.simpleDescription)
extension Int:ExampleProtocol{
var simpleDescription:String{
return "The number is (self)"
}
mutating func adjust(){
self += 50
}
}
println(7.simpleDescription)
extension String:ExampleProtocol{
var simpleDescription:String{
return "My name is (self)"
}
mutating func adjust(){}
}
print("XingXing".simpleDescription)