/*
只有将协议中的实例方法标记为mutating才允许结构体、枚举的具体实现修改自身内存
类在实现方法时不用加mutating,枚举、结构体才需要加mutating
*/protocolPersonFrame{mutatingfuncspeak()}classPerson1:PersonFrame{var age:Int=1funcspeak(){
age=2print("i am \(age)")}}structPerson2:PersonFrame{var age:Int=1mutatingfuncspeak(){
age=3print("i am \(age)")}}var p1=Person1()
p1.speak()
i am 2var p2=Person2()
p2.speak()
i am 3
/*
枚举遵守CaseIterable协议可以实现遍历枚举值
*/enumTest:CaseIterable{case up,down,left,right}let test =Test.allCases
print(test.count)
输出:4for t in test{print(t)}
输出:
up
down
leftright
1.9-CustomStringConvertible协议
/*
遵守CustomStringConvertible、 CustomDebugStringConvertible协议,都可以自定义实例的打印字符串
print调用的是CustomStringConvertible协议的description
debugPrint、po调用的是CustomDebugStringConvertible协议的debugDescription
*/classPerson:CustomStringConvertible,CustomDebugStringConvertible{var age =0var description:String{"person_\(age)"}var debugDescription:String{"debug_person_\(age)"}}var person =Person()print(person)debugPrint(person)
输出:
person_0
debug_person_0
1.10-Any、AnyObject
/*
Swift提供了2种特殊的类型:Any、AnyObject
Any:可以代表任意类型(枚举、结构体、类,也包括函数类型)
AnyObject:可以代表任意类类型(在协议后面写上: AnyObject代表只有类能遵守这个协议)
在协议后面写上: class也代表只有类能遵守这个协议
*/classTest{}var stu:Any=10
stu ="test"
stu =Test()// 创建1个能存放任意类型的数组var data =[Any]()
data.append(1)
data.append(3.14)
data.append(Test())
data.append("test")
data.append({10})
//self代表当前类型classPerson{var age =1staticvarcount=2funcrun(){print(self.age)print(Self.count)}}protocolLiveable{functest()->Self}classPerson:Liveable{requiredinit(){}functest()->Self{type(of:self).init()}}classChild:Person{}var p =Person()print(p.test())//test.Personvar cld =Child()print(cld.test())//test.Child