简体   繁体   中英

Should I define computed property of inside of protocol if the extension with implementation follows?

What's the difference between:

protocol DashboardTargetInfo: TargetInfo {
    var apiVersion: Int { get }
}

extension DashboardTargetInfo {
    var apiVersion: Int {
        5
    }
}

And the one without computed property included in protocol definition

protocol DashboardTargetInfo: TargetInfo {}

extension DashboardTargetInfo {
    
    var apiVersion: Int {
        5
    }
}

Should I include the definition of the computed "apiVersion" property if the extension definition is following? Is there any difference between those two snippets of code?

In the first version apiVersion is part of the protocol and any conforming types must implement the property or use the default one. In the second one this is just a computed property that is available for types conforming to it and not part of the protocol.

An example:

struct Test1: DashboardTargetInfo { var apiVersion: Int }
struct Test2: DashboardTargetInfo { var apiVersion: Int { 10 } }

let values: [DashboardTargetInfo] = [Test1(apiVersion: 42), Test2()]
print(values.map(\.apiVersion))

With the first version of the protocol we get the values of the conforming types

[42, 10]

But if our types conforms to the second example then apiVersion is not part of the protocol so only the default computed value is used

[5, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM