How can I unwrap an optional value inside a binding in Swift?

大憨熊 提交于 2020-11-24 12:08:40

问题


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


回答1:


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

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



来源:https://stackoverflow.com/questions/58297176/how-can-i-unwrap-an-optional-value-inside-a-binding-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!