SwiftUI 中的可选绑定

joh*_*doe 3 swift swiftui

我正在尝试在 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 }
        )

    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

在此处输入图片说明

New*_*Dev 5

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

Binding<Value>(...)
Run Code Online (Sandbox Code Playgroud)

但预计回报为Binding<T>.

因此,您可以显式使用Binding<T>(...),也可以让编译器根据函数的返回值来推断它:

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

或者,只需使用Value代替T

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