Protocol Extension

2019-06-29  本文已影响0人  盖小聂

如果在接口中只定义了一个方法,而在接口扩展中实现了额外的方法,事情就变得有趣起来了。

protocol A {
    func method1()
}

extension A {
    func method1() {
        print("hi")
    }
    func method2() {
        print("hi")
    }
}

struct B: A {
    func method1() {
        print("Hello")
    }
    func method2() {
        print("Hello")
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //类型推断得到是实际类型,那么类型中的实现将被调用;
        //如果类型中没有实现,那么接口扩展中的默认实现将被使用
        let b = B()
        b.method1()
        b.method2()
        
        let a = b as A
        //类型推断得到的是接口,而不是实际类型,并且方法在接口中进行了定义,那么类型中的实现将被调用;
        //如果类型中没有实现,那么接口扩展中的默认实现被使用
        a.method1()
        
        //类型推断得到的是接口,而不是实际类型,方法没有在接口中定义,
        //扩展中的默认实现将被调用
        a.method2()
        
        /*
        输出的结果:
         Hello
         Hello
         Hello
         hi
        */
    }
}

补充说明:

上一篇 下一篇

猜你喜欢

热点阅读