Skip to content

Instantly share code, notes, and snippets.

@mpvosseller

mpvosseller/example.swift

Last active Feb 28, 2018
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@mpvosseller mpvosseller commented Feb 28, 2018

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
You can’t perform that action at this time.