[swift-users] Conforming to the protocol requirements with implicitly unwrapped optional

Anton Bronnikov anton.bronnikov at me.com
Sun May 28 23:37:03 CDT 2017


Hi All,

If I have a protocol with a property requirement such as:

protocol Foo {
    var value: Int { get }
}

.. and I need to conform to it using an implicitly unwrapped optional like:

struct Bar : Foo {
    let value: Int! = nil
}

.. then the compiler fails with an error:

Playground execution failed: error: scratchpad.playground:5:8: error: type 'Bar' does not conform to protocol 'Foo'
struct Bar : Foo {
       ^

scratchpad.playground:2:9: note: protocol requires property 'value' with type 'Int'; do you want to add a stub?
    var value: Int { get }
        ^

scratchpad.playground:6:9: note: candidate has non-matching type 'Int!'
    let value: Int! = nil
        ^
Technically, I understand why the error, and currently work around it with a cumbersome:

struct Bar : Foo {
    var value: Int { return _value! }
    let _value: Int? = nil
}

However, I keep wondering - would it not be making sense to accept implicitly unwrapped optionals as a conformance to be base-type requirements?  It sort of works just like that in all other parts of the language.

Or in other words, is this by design, or should I probably create an issue for this?

Thank you.
Cheers,
Anton

P.S. The example is oversimplified for the sake of clarity, in practice the property just has to be an optional - implicitly unwrapped or not - because it’s a part of the composite that holds unowning reference to its container object.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170529/db27934b/attachment.html>


More information about the swift-users mailing list