[swift-users] Optional conformance warnings with Protocols

Rod Brown rodney.brown6 at icloud.com
Sun Jul 24 15:23:30 CDT 2016

Thanks Brent,

Yes, I hope this is something that can get cleared up eventually. As you say, hopefully when ImplicitlyUnwrappedOptional goes away we can clear this up.

At least in the case you showed, the optionality is completely different. X will hand you back an object, rather than an Optional (enum) of that object. I understand why, semantically, they are different, and why the compiler may be unable/unwilling to vary the type on return.

In the case of an implicitly unwrapped optional, though, they should theoretically be the same type - Optional<String> - with only the unwrapping behaviour differing. I expect this is part of the reason Implicitly unwrapped optional is dying out as a separate type.

As Xin Zhang points out, this is only a warning, not an error, so I'm gonna accept it. It works correctly, at least.

- Rod

On 25 Jul. 2016, at 2:05 am, Brent Royal-Gordon <brent at architechies.com> wrote:

>> On Jul 23, 2016, at 9:09 PM, Rod Brown via swift-users <swift-users at swift.org> wrote:
>> However, the compiler still emits a warning. "Type of 'title' has different optionality than expected by protocol ‘MKAnnotation' "
> Yes, I've encountered this error before. Example:
>  1> import Foundation
>  2> @objc protocol P { var x: String? { get } }
>  3> class X: NSObject, P { let x = "" }
> error: repl.swift:3:28: error: type of 'x' has different optionality than required by protocol 'P'
> class X: NSObject, P { let x = "" }
>                           ^
> Swift doesn't appear to allow covariance and contravariance when satisfying protocol requirements, or at least forbids it in optionals. It's a shame, because at least in a theoretical sense it's perfectly consistent.
> Unfortunately, you've pretty much just got to do what the compiler tells you in this case. I expect that you'll at least be able to use `!` instead of `?` once ImplicitlyUnwrappedOptional is fully removed, but I don't believe we've gotten there yet.
> -- 
> Brent Royal-Gordon
> Architechies
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160725/b87b526e/attachment.html>

More information about the swift-users mailing list