I'm building an app using SwiftUI and would like a way to convert a Binding<Value?>
to a Binding<Value
>.
In my app I have an AvatarView
which knows how to render an image for a particular user.
struct AvatarView: View {
@Binding var userData: UserData
...
}
My app holds a ContentView
that owns two bindings: a dictionary of users by id, and the id of the user whose avatar we should be showing.
struct ContentView: View {
@State var userById: Dictionary<Int, UserData>
@State var activeUserId: Int
var body: some View {
AvatarView(userData: $userById[activeUserId])
}
}
Problem: the above code doesn't combine because $userById[activeUserId]
is of type Binding<UserData?>
and AvatarView
takes in a Binding<UserData>
.
Things I tried...
$userById[activeUserId]!
doesn't work because it's trying to unwrap a Binding<UserData?>
. You can only unwrap an Optional
, not a Binding<Optional>
.
$(userById[activeUserId]!)
doesn't work for reasons that I don't yet understand, but I think something about $
is resolved at compile time so you can't seem to prefix arbitrary expressions with $
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…