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

Zhao Xin owenzx at gmail.com
Mon May 29 01:20:31 CDT 2017


Why you have to use `unwrapped optional` at the first place? If you have to
use it, it means it could be nil. So it won't conform the protocol, which
requires the `value` never nil.

Zhaoxin

On Mon, May 29, 2017 at 12:37 PM, Anton Bronnikov via swift-users <
swift-users at swift.org> wrote:

> 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.
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170529/382ee278/attachment.html>


More information about the swift-users mailing list