1.基本使用
(1)定義一個協議
protocol TryShowDelegate {
func returnString()
func returnShowString(str:String)
}
(2)定義一個代理屬性,遵守協議
class ViewController:UIViewController,TryShowDelegate{
var delegate:TryShowDelegate?
}
(3)判斷代理是否實現,呼叫
delegate?.returnString()
delegate?.returnShowString(str:"這樣的啊")
(4)方法的實現
func returnShowString(str:String) {
print(str)
}
func showMessage() {
print("showMessage")
}
2.swift可選代理
如上,swift代理的宣告和使用,還是感覺比oc要簡潔很多,但是,swift現在是沒有可選代理的,也就是說,你代理中,定義的方法,每一個都要在呼叫者中進行實現,不然無法編譯。
@objc protocol showMessageDelegate {
func showMessage()// 必須實現的方法
@objc optionalfuncshowOpttionShowMessage()// 可選實現的方法
}
class ViewController:UIViewController,TryShowDelegate,showMessageDelegate{
var showDelegate:showMessageDelegate?
}
showDelegate=self
showDelegate?.showMessage()
//showDelegate?.showOpttionShowMessage!()
func showMessage() {
print("showMessage")
}
//func showOpttionShowMessage() {
//print("showOpttionShowMessage")
//}
3.將protocol的方法宣告為mutating
swift的protocol不僅可以被class實現,也適用於struct 和 enum。因為這個原因,我們在給別人用哪個協議的時候就要多考慮是否用mutating修飾。mutating 關鍵字修飾方法是為了能夠該方法中修改struct或是emum的變數,如果沒在協議裡寫mutating的話,別人用struct或者是enum來實現協議的話,就不能改變自己的變數了
protocol Vehicle {
var numberOfWheels:Int{get}
var color:UIColor{get set}
mutating func changeColor()
}
struct MyCar:Vehicle{
let numberOfWheels:Int=4
var color =UIColor.blue
mutating func changeColor() {
color= .red
}
}
如果把protocol定義中的mutating去掉的話,MyCar就不能編譯成功,另外在使用class就不需要新增mutating修飾,因為class可以隨意更改自己的成員變數。