はじめに
Bindingの中身がオプショナルで型が違うので渡せないという問題に遭遇しました。
解決策を記録しておきます。
問題点
Cannot convert value of type 'Binding<String>' to expected argument type 'Binding<String?>'
import SwiftUI
struct ContentView: View {
@State var text: String = "サンプル"
var body: some View {
SubView(text: $text)
}
}
struct SubView: View {
@Binding var text: String?
var body: some View {
Text(text ?? "")
}
}
実装
import SwiftUI
struct ContentView: View {
@State var text: String = "サンプル"
var body: some View {
SubView(text: .init(
get: { text },
set: { text = $0 ?? "" }
))
}
}
struct SubView: View {
@Binding var text: String?
var body: some View {
Text(text ?? "")
}
}
おわり
これは公式で対応してもらいたいですね