Last active
February 28, 2018 19:53
-
-
Save mpvosseller/02c6bbf853442c5de3c2fc9adc139e00 to your computer and use it in GitHub Desktop.
When implementing a protocol property that returns an optional value you must explicitly declare the type (as an optional) in your implementation. See below comment for details.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol MyProtocol { | |
var name: String? { get } | |
} | |
extension MyProtocol { | |
var name: String? { | |
return "aDefaultName" | |
} | |
} | |
struct MyImpl: MyProtocol { | |
let name = "myName" // XXX things break later because we don't explcitly set the type here as String? | |
//let name : String? = "myName" // This fixes it | |
} | |
let implRef = MyImpl() | |
print(implRef.name) // prints "myName" as expected | |
let protocolRef = implRef as MyProtocol | |
print(protocolRef.name) // prints "Optional("aDefaultName")" somewhat unexpectedly | |
// Had there not been a default implementation of MyProtocol the compiler would have noticed | |
// the type mismatch and complained that MyImpl didn't conform to MyProtocol. It would be nice | |
// if the compiler could detect when a function/property conflicts with a default implementation | |
// in this way. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When implementing a protocol property that returns an optional value you must explicitly declare the type (as an optional) in your implementation. This is easy to miss if there is a default implementation and you implement the property with a simple assignment. The compiler doesn't warn you because you still conform to the protocol (via the default implementation) and accessing the property only fails when using a protocol reference.