-
Hi there! Given the following code sample, I just can't seem to get around subscripting struct Foo {
var bar: Bar
}
struct Bar {
var id: UUID
}
struct State {
@Shared
var foo: Foo?
func getSharedBar() -> Shared<Bar?> {
$foo.bar // Value of optional type 'Foo?' must be unwrapped to refer to member 'bar' of wrapped base type 'Foo'
$foo?.bar // Cannot use optional chaining on non-optional value of type 'Shared<Foo?>'
_ = Shared($foo)?.bar // Here I get Shared<Bar>?
}
} Is this not supported or am I not seeing what's right in front of me…? 😅 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi @Pomanks, the last line you have is the way to do it, you just need to unwrap the shared: @Shared var foo: Foo?
if let sharedFoo = Shared($foo) {
let sharedBar = sharedFoo.bar
} This is necessary because you have to deal with the optionality of This is also how things works in SwiftUI with |
Beta Was this translation helpful? Give feedback.
Ah I see, sorry I misread that.
What you are trying to do isn't really possible. Suppose you could get a
bar: Shared<Bar?>
from afoo: Shared<Foo?>
, and suppose that thefoo
was currentlynil
. What would happen if you wrote a non-nil
value to thebar
? It would somehow need to construct aFoo
and stick thebar
into it, which can't happen generically. So it would have no choice but to discard that value and keepbar
asnil
.It's worth mentioning that this is a bit different from the behavior of
foo?.bar
. Because clearly one can dofoo?.bar = Bar()
even withfoo
isnil
, and theBar()
is just discarded. But at least at the call site you can plainly seefoo?
so you know an optional is involved…