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

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

问题描述

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

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]BindingAvatarView 类型接受 Binding.

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.您只能解包 Optional,而不是 Binding.

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

推荐答案

您可以使用 this initialiser,它似乎处理这种确切的情况 - 将 Binding 转换为 Binding?:

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?.

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天全站免登陆