I have a ~Copyable struct in an Optional on self

I have an implicitly unwrapped optional that contains an instance of ~Copyable struct.

struct Foo: ~Copyable {
     let inner: Double
}

class Bar {
    var foo: Foo! 
}

Now, it absolutely has to be an implicitly unwrapped type because it's a late init value - in order to constuct it I need access to self.

Now, everytime I try to read it, I get a compiler error:

if foo.inner > 0.0 {

Error: Cannot consume noncopyable stored property 'self.colorStopsAnimation' of a class

Does this mean, that you can not unwrap an optional without copying or consuming?

Can you guys suggest me what can I do here without changing design of the system - I really benefit from late-init semantics through usage of implicitly unwrapped optionals...

Rust referential binding comes to mind, but we don't have that in Swift, right?

1 Like

Looks like this is currently an artificial limitation of IUOs — I'd believe that it desugars to unsafelyUnwrapped, which has a note that it should borrow, but doesn't at the moment.

But since the Double stored inside is itself copyable, you can grab it in a separate expression:

guard let inner = foo?.inner else {
    return
}

if inner >= 0.0 {
    // blah            
}
2 Likes

Is it possible to replace IUO with temporary placeholder value?

class Bar {
    var foo: Foo

    init() {
        // placeholder value
        foo = Foo(inner: -1)

        // other code

        foo = Foo(inner: 42)
    }
}
1 Like