iOS - swift 拓展問(wèn)題

在學(xué)習(xí)swift拓展的時(shí)候發(fā)現(xiàn)跟OC不同點(diǎn)就是不能和拓展類函數(shù)名同名,那如何才能使用拓展來(lái)替換原函數(shù)名呢?

建議先看類與結(jié)構(gòu)體 方法的派發(fā)這一篇

拓展替換原方法

oc:由于拓展是運(yùn)行時(shí)加載,所以函數(shù)同名則會(huì)替換掉原來(lái)的函數(shù)
swift:由于拓展是靜態(tài)派發(fā),所以函數(shù)名不能與其他方法同名。

思考:不修改函數(shù)體,如何才能做到讓person.hello()執(zhí)行helloExtension()方法

class Person{
    func hello(){
        print("hello")
    }
}
extension Person{
    func helloExtension(){
        print("helloExtension")
    }
}
person.hello()
person.helloExtension()

讓函數(shù)變?yōu)閯?dòng)態(tài)性 在使用_dynamicReplacement進(jìn)行動(dòng)態(tài)調(diào)換

class Person{
    @objc dynamic func hello(){
        print("hello")
    }
}
extension Person{
    @_dynamicReplacement(for:hello)
    func helloExtension(){
        print("helloExtension")
    }
}
let person = Person()
person.hello()
person.helloExtension()

原理:會(huì)生成一個(gè)結(jié)構(gòu)體存放helloExtension 函數(shù)地址。遇到調(diào)用hello則轉(zhuǎn)為調(diào)用helloExtension,通常dynamic會(huì)搭配@objc出現(xiàn)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容