方法协议:定义时没有花括号执行体,实现仅要求名称相同
作用:可以让一个类/机构提/枚举的方法,分解为更小的组合,从而更灵活
// 类型方法协议:前缀总是static 不能用class
protocol Amethod {
static func foo()
}
class A: Amethod {
static func foo() {
print("aaaa")
}
}
class A1: Amethod {
class func foo() {
print("A1A1A1")
}
}
A.foo()
A1.foo()
import Foundation
// 实例方法协议
protocol RandomGeneratable {
func randomNumber() -> Int
}
struct RandomNumber : RandomGeneratable {
func randomNumber() -> Int {
return Int(arc4random())
}
}
struct RandomNumberInSix : RandomGeneratable {
func randomNumber() -> Int {
return Int(arc4random())%6
}
}
let random1 = RandomNumber()
random1.randomNumber()
let random2 = RandomNumberInSix()
random2.randomNumber()
// 结构体/枚举的“变异方法协议” mutating 方法协议更改属性的值 要加mutating
protocol Switchable {
mutating func onOff()
}
enum mySwitch:Switchable {
mutating func onOff() {
switch self {
case .off:
self = .on
default:
self = .off
}
}
case on,off
}