【问题标题】:Optional Binding in SwiftUISwiftUI 中的可选绑定
【发布时间】:2020-05-31 00:02:48
【问题描述】:

我正在尝试在 Binding 上创建一个扩展,以便我可以打开并绑定到可选的 Binding。

我有以下从 StackOverFlow 获得的代码。

extension Binding {

    static func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {

        return Binding(
            get: { lhs.wrappedValue ?? rhs },
            set: { lhs.wrappedValue = $0 }
        )

    }
}

但我收到以下错误:

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    当你使用Binding(...)的初始化器时,它会推断出它的类型参数是Value(记住,Binding本身是一个泛型,Value是它的类型参数),所以实际上它是这样做的:

    Binding<Value>(...)
    

    但期望返回为Binding&lt;T&gt;

    所以,你既可以显式使用Binding&lt;T&gt;(...),也可以让编译器根据函数的返回值来推断:

    static func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {
       .init(get { lhs.wrappedValue ?? rhs },
             set { lhs.wrappedValue = $0 })
    }
    

    或者,只需使用Value 而不是T

    static func ??(lhs: Binding<Optional<Value>>, rhs: Value) -> Binding<Value> {
       Binding(get { lhs.wrappedValue ?? rhs },
               set { lhs.wrappedValue = $0 })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2022-07-18
      相关资源
      最近更新 更多