I have a struct with a member named email
of type String
, and a protocol with a member named email
of type String?
. I would think it should be trivial to have the struct conform to that protocol, since it has the necessary information, but I'm being blocked by the compiler. Here's a pared down example I put together in a playground:
struct SimpleStruct {
let email: String
}
protocol SimpleProtocol {
var email: String? { get }
}
// Type 'SimpleStruct' does not conform to protocol 'SimpleProtocol'
extension SimpleStruct: SimpleProtocol {}
The error specifically says:
Candidate has non-matching type 'String'
It also offers a fix:
Do you want to add protocol stubs?
But unsurprisingly that leads to a redeclaration error.
extension SimpleStruct: SimpleProtocol {
var email: String? {
// Invalid redeclaration of 'email'
}
}
I understand that String
and Optional<String>
are different types, but I would expect that simply saying SimpleStruct
conforms to SimpleProtocol
with no additional code should compile, for the same reason that I can pass a string to a function that expects an optional string. Can someone explain why I'm mistaken?
Note: I realize I can get around this issue in a number of ways, most notably just renaming the email
field in SimpleProtocol
. But I'd like to understand why this is necessary as well as know if there's a more elegant solution.