Skip to content

Instantly share code, notes, and snippets.

@mpvosseller
Last active February 28, 2018 19:53
Show Gist options
  • Save mpvosseller/02c6bbf853442c5de3c2fc9adc139e00 to your computer and use it in GitHub Desktop.
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.
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.
@mpvosseller
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment