Swift static characteristics Protocol on extension

Experimental sample code

//声明一个协议
protocol SharedString {
    func methodForOverride() -> Void
    func methodWithoutOverride() -> Void
}

//扩展协议,实现默认实现
//注意方法methodWithoutOverride 中调用了 methodForOverride 方法,这里有一个上写文切换的问题
extension SharedString {
    func methodForOverride() -> Void {
        print("��")
    }

    func methodWithoutOverride() -> Void {
        print("��")
        methodForOverride()
        print("��")
    }
}

//在String类的扩展中遵守并实现协议
extension String:SharedString {
    func methodForOverride() -> Void {
        print(self)
    }
}

//创建字符串并切换上下文到SharedString协议
let Shared:SharedString = "hello"

Shared.methodForOverride()
Shared.methodWithoutOverride()

Execution of different code conversion obtained are summarized

Case number Agreement statement method Protocol extensions in the default implementation Follow the protocol class rewrite Following the experimental protocol property (switch contexts) Result of the method execution method
1 YES NO YES NO Follow the protocol class method overridden
2 YES YES YES YES Follow the protocol class method overridden
3 YES NO YES YES Follow the protocol class method overridden
4 NO NO YES NO Follow the protocol class method overridden
5 YES YES YES NO Follow the protocol class method overridden
6 NO YES NO YES The default extension protocol implementation
7 NO YES NO NO The default extension protocol implementation
8 YES YES NO YES The default extension protocol implementation
9 YES YES NO NO The default extension protocol implementation
10 NO YES YES YES The default extension protocol implementation
11 NO YES YES NO 1 and 2 are methods of protocol extension. The method, overridden in class to follow, a method call, the method follows the protocol class is rewritten. Method 2 is not rewritten, but in the agreement called Tier 2 method, this time, when the calling method 1 method 2 is still the default protocol extensions to achieve
12 NO NO YES YES ERROR
13 NO NO NO YES ERROR
14 NO NO NO NO ERROR
15 YES NO NO NO ERROR
16 YES NO NO YES goal conversions

The method of rewriting protocol extensions defined in the protocol extensions to retain the static characteristics of the original method is rewritten version of cartridge, you can obtain different versions by switching contexts, while not rewriting the method, which can ensure invariance.

We can follow a principle, to those who want to be overridden method defined in the agreement, those who do not want to define and implement the replication method on protocol extensions.

Published 139 original articles · won praise 35 · views 410 000 +

Guess you like

Origin blog.csdn.net/wxs0124/article/details/73742465