美文网首页
iOS - swift 拓展问题

iOS - swift 拓展问题

作者: Th丶小伟 | 来源:发表于2022-09-02 11:01 被阅读0次

    在学习swift拓展的时候发现跟OC不同点就是不能和拓展类函数名同名,那如何才能使用拓展来替换原函数名呢?

    建议先看类与结构体 方法的派发这一篇

    拓展替换原方法

    oc:由于拓展是运行时加载,所以函数同名则会替换掉原来的函数
    swift:由于拓展是静态派发,所以函数名不能与其他方法同名。

    思考:不修改函数体,如何才能做到让person.hello()执行helloExtension()方法

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

    让函数变为动态性 在使用_dynamicReplacement进行动态调换

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

    原理:会生成一个结构体存放helloExtension 函数地址。遇到调用hello则转为调用helloExtension,通常dynamic会搭配@objc出现

    相关文章

      网友评论

          本文标题:iOS - swift 拓展问题

          本文链接:https://www.haomeiwen.com/subject/ayienrtx.html