无法将类型“Binding<Double>”的值转换为预期参数类型“Binding<Double?>”

kus*_*uya 7 swift swiftui

有时我想将一个值传递给 @Binding 属性,有时我不想。

struct ParentView: View {
    @State var prop = 0.0

    var body: some View {
        ChildView(prop: $prop) // Error: Cannot convert value of type 'Binding<Double>' to expected argument type 'Binding<Double?>'
        ChildView() // sometimes I do not want pass anything
    }
}

struct ChildView: View {
    @Binding var prop: Double?

    init(prop: Binding<Double?> = .constant(nil)) {
        _prop = prop
    }

    var body: some View {
        Text("Child View")
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案可能是以下代码。

@State var prop: Double? = 0.0
Run Code Online (Sandbox Code Playgroud)

但是,如果可能的话,我不想将 @State 属性定义为可选类型。
还有其他办法吗?

Asp*_*eri 3

这是一个解决方案,可以消除带和不带值绑定的歧义。

使用 Xcode 11.4 / iOS 13.4 进行测试

struct ChildView: View {
    @Binding var prop: Double?

    init() {
        _prop = .constant(nil)
    }

    init(prop: Binding<Double>) {
        _prop = Binding(prop)
    }

    var body: some View {
        Group {
            if prop != nil {
                Text("Child View: \(prop!)")
            } else {
                Text("Child View")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)