事情的起因是這樣的:
如果想配置當(dāng)前vc出現(xiàn)時(shí)狀態(tài)欄的樣式我們可以這樣做:
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
有的vc的狀態(tài)欄是白色,有的是黑色号俐,總這樣override一個(gè)方法也是挺礙眼的泌豆,那能不能把這個(gè)代碼移進(jìn)protocol的extension中呢?
這樣的話用起來(lái)就像這樣:
class XxxViewController:UIViewController,LightStatusBarStyle {
}
想想實(shí)現(xiàn)起來(lái)很簡(jiǎn)單嘛:
protocol LightStatusBarStyle:class {
func preferredStatusBarStyle() -> UIStatusBarStyle
}
extension LightStatusBarStyle where Self:UIViewController {
func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
但是運(yùn)行起來(lái)的時(shí)候吏饿,你會(huì)發(fā)現(xiàn)這個(gè)方法沒(méi)有執(zhí)行踪危。
于是你再觀察了一下,忽然發(fā)覺(jué)可能是少了<code>override</code>猪落。
我就直接把結(jié)果貼出來(lái)吧:
你會(huì)得到一個(gè)error贞远。
extension之前還好好的,怎么override就不行了呢笨忌?
真相到底是什么蓝仲?
是Xcode的抽風(fēng),是Swift的忽然自我官疲,還是Mac太久沒(méi)有重啟袱结?
歡迎進(jìn)入本期的:
真相就是:
在extension中可以添加新函數(shù),但是不能override一個(gè)已有的函數(shù)
官方是這么說(shuō)的:
Extensions can add new functionality to a type, but they cannot override existing functionality.
總而言之就是:
one more thing
不過(guò)我們可以再回憶一下OC的runtime途凫。
可以對(duì)方法增加dynamic修飾符聲明為OC的方法擎勘,這樣就可以曲線的在extension中使用override了:
class A : NSObject {
dynamic func doThing() {
print("dothing super class")
}
}
class B: A {
}
extension B {
override func doThing() {
print("dothing sub class")
super.doThing()
}
}
歡迎關(guān)注我的微博:@沒(méi)故事的卓同學(xué)
相關(guān)鏈接:
http://stackoverflow.com/questions/38213286/overriding-methods-in-swift-extensions
http://stackoverflow.com/questions/37492897/swift-dispatch-to-overridden-methods-in-subclass-extensions