如何在Swift的绑定中解开可选值? [英] How can I unwrap an optional value inside a binding in Swift?

查看:92
本文介绍了如何在Swift的绑定中解开可选值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SwiftUI构建应用程序,并且想要一种将Binding<Value?>转换为>的方法.

I'm building an app using SwiftUI and would like a way to convert a Binding<Value?> to a Binding<Value>.

在我的应用中,我有一个AvatarView,它知道如何为特定用户渲染图像.

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

  ...
}

我的应用程序包含一个ContentView,它具有两个绑定:一个按ID排列的用户词典,以及一个我们应显示其头像的用户的ID.

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])
  }
}

问题:上面的代码没有合并,因为$userById[activeUserId]Binding<UserData?>类型,而AvatarView接受了Binding<UserData>.

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]!不起作用,因为它正在尝试打开Binding<UserData?>的包装.您只能打开Optional的包装,而不能打开Binding<Optional>的包装.

  • $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]!)由于我尚不了解的原因而无法使用,但我认为有关$的某些问题在编译时已解决,因此您似乎无法在$前面加上任意表达式.

$(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 $.

推荐答案

您可以使用此初始化程序,似乎可以处理这种情况-将Binding<T?>转换为Binding<T>?:

You can use this initialiser, which seems to handle this exact case - converting Binding<T?> to Binding<T>?:

var body: some View {
    AvatarView(userData: Binding($userById[activeUserId])!)
}

我已经使用!强制展开,就像您尝试进行的一样,但是您可以根据需要随意展开nil.表达式Binding($userById[activeUserId])的类型为Binding<UserData>?.

I have used ! to force unwrap, just like in your attempts, but you could unwrap the nil however you want. The expression Binding($userById[activeUserId]) is of type Binding<UserData>?.

这篇关于如何在Swift的绑定中解开可选值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆