[swift-users] A confusing protocol extension behaviour/bug

Toni Suter tonisuter at me.com
Tue Jan 2 03:12:47 CST 2018


Hi Marc,

>> The second class defines a static property that looks like it is 'overriding' the static property from
>> the protocol extension, but since the types don't match (String vs. String?), it sort of 'overloads'
>> the property (similar to function overloading). Nevertheless, the class still fulfills the requirements
>> of the Trackable protocol, by inheriting the static property from the protocol extension.
> 
> Isn’t this a compiler bug?
> 
> I didn’t realise that overloading properties was a thing? I’m pretty sure it isn’t, in which case the compiler should choke because there are two properties of the same name but divergent types available on the type. 
> 
> This behaviour seems to create major hard-to-detect hazards when using protocol extensions, which seems against the spirit of Swift. 

Yeah, I guess overloading might not be the right term. You're right, properties can't be overloaded in general. For example:

struct S {
    static var x: Int { return 2 }
    static var x = ""			// error: invalid redeclaration of 'x'
}

You can only 'overload' properties that are inherited from a protocol extension. 

protocol P {}
extension P {
    static var x: Int { return 2 }
}
struct S: P {
    static var x = ""
}

I am not exactly sure why this is allowed, but maybe someone from the Swift team can help.

Best regards,
Toni
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20180102/ca55e1bd/attachment.html>


More information about the swift-users mailing list