首页 > 解决方案 > 如何将可选类型绑定到非可选类型

问题描述

Xcode 说无法将类型 'Binding<String?>' 的值转换为预期的参数类型 'Binding<String>'

struct CustomContentView: View {
    @State var queryItem = URLQueryItem.init(name: "key", value: nil)

    var body: some View {
//queryItem.value is optional string
        TextField.init("value", text: $queryItem.value)
//Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'
    }
}

截屏

标签: iosbindingswiftuistateoptional

解决方案


使用以下

var body: some View {
    TextField("url", text: Binding(
        get: { self.queryItem.value ?? ""},
        set: { self.queryItem.value = $0 } )
    )
}

推荐阅读