SwiftUI中的可选绑定

时间:2020-05-31 00:02:48

标签: 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 }
        )

    }
}

但是出现以下错误:

enter image description here

1 个答案:

答案 0 :(得分:5)

使用Binding(...)的初始化程序时,它会推断其类型参数为Value(请记住,Binding本身是泛型,而Value是其类型参数),因此实际上是这样做的:

Binding<Value>(...)

但希望收益为Binding<T>

因此,您可以显式使用Binding<T>(...),或者只是让编译器根据函数的返回值进行推断:

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