0
1

More than 1 year has passed since last update.

【SwiftUI】OptionalのBindingをアンラップする

Posted at

はじめに

Bindingの中身がオプショナルで型が違うので渡せないという問題に遭遇しました。
解決策を記録しておきます。

問題点

型が違うので渡せないわけですね
スクリーンショット 2023-08-25 22.47.42.png

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

おわり

これは公式で対応してもらいたいですね

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1