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@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to