[swift-users] [Bug or ByDesign?] unowned optional values not allowed

Zhao Xin owenzx at gmail.com
Tue Jul 5 20:25:54 CDT 2016


According to you description, you should use


weak var parent:A!



Zhaoxin

On Mon, Jul 4, 2016 at 2:29 PM, Karl via swift-users <swift-users at swift.org>
wrote:

> Currently it’s not possible to have an unowned optional value. E.g:
>
> class A {
>           unowned var parent : A?   // ‘unowned’ may only be applied to
> class and class-bound protocol types, not ‘A?'
>           deinit {
>             if let p = parent { print("Bye, mom!") }
>             print("deallocating")
>         }
> }
>
> Sometimes you want an unowned value, but it doesn’t actually need to be
> set.
>
> In a specific case I was working on, we wanted to use a private embedded
> struct to wrap some functionality away as a unit, but we need a reference
> back to the enclosing instance. We could have a weak reference, but that
> comes with additional overheads, and it’s unnecessary because that struct
> code will all get inlined and the reference will just be a pointer back to
> ‘self’ (it would be cool if the compiler could detect that and just not
> emit the variable at all, but I don’t think it’ll do that). In any case, in
> order to initialise it with the parent that reference needs to be an
> optional/implicitly-unwrapped-optional (so that it can be initialised to
> nil and then set after the parent calls super.init).
>
> Given that weak optionals work, I’m tempted to think it’s a bug, but I’m
> asking in case it was intentionally omitted.
>
>
> _______________________________________________
> 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/20160706/b73333fb/attachment.html>


More information about the swift-users mailing list