[英]How can I unwrap an optional value inside a binding in Swift?
I'm building an app using SwiftUI and would like a way to convert a Binding<Value?>
to a Binding<Value
>.我正在使用 SwiftUI 构建一个应用程序,并且想要一种将Binding<Value?>
转换为Binding<Value
> 的方法。
In my app I have an AvatarView
which knows how to render an image for a particular user.在我的应用程序中,我有一个AvatarView
,它知道如何为特定用户呈现图像。
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.我的应用程序拥有一个ContentView
,它拥有两个绑定:一个按 id 的用户字典,以及我们应该显示其头像的用户的 id。
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>
.问题:上面的代码没有合并,因为$userById[activeUserId]
是Binding<UserData?>
类型,而AvatarView
接受Binding<UserData>
。
Things I tried...我试过的东西...
$userById[activeUserId]!
doesn't work because it's trying to unwrap a Binding<UserData?>
.不起作用,因为它试图解开Binding<UserData?>
。 You can only unwrap an Optional
, not a Binding<Optional>
.您只能打开Optional
,而不是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 $
. $(userById[activeUserId]!)
由于我还不明白的原因不起作用,但我认为关于$
的某些内容在编译时已解决,因此您似乎无法为任意表达式添加前缀$
。
You can use this initialiser , which seems to handle this exact case - converting Binding<T?>
to Binding<T>?
您可以使用这个初始化程序,它似乎可以处理这种确切的情况 - 将Binding<T?>
转换为Binding<T>?
: :
var body: some View {
AvatarView(userData: Binding($userById[activeUserId])!)
}
I have used !
我用过!
to force unwrap, just like in your attempts, but you could unwrap the nil
however you want.强制解包,就像在您的尝试中一样,但是您可以根据需要解包nil
。 The expression Binding($userById[activeUserId])
is of type Binding<UserData>?
表达式Binding($userById[activeUserId])
的类型是Binding<UserData>?
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.