0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

@Bindingってなに!?!? - iOS Swift

Posted at

色々漁ってたら@Bindingなる表記が出てきました。
@って付いてたら身構えちゃう癖ができそうです。
なにこれ。。。

橋渡し

Use a binding to create a two-way connection between a property that stores data, and a view that displays and changes the data. A binding connects a property to a source of truth stored elsewhere, instead of storing data directly.

SwiftUI/Binding Overviewより

簡単に訳すと「bindingは、データを保存するプロパティとデータの表示と変更を担うビューを繋ぐ存在です。bindingを使用することで、直接データを保存するのではなく、信頼できる唯一の情報源を参照することができます。」ということだそうです。

???
なにこれ。夢なの??

繋ぐ?

こちらのコードはテキストとボタンを縦に表示します。

struct ContentView: View {
    @State var isClicked = false
    
    var body: some View {
        VStack {
            Text(isClicked ? "ON" : "OFF")
            
            ChildView(isClicked: $isClicked)
        }
    }
}

struct ChildView: View {
    @Binding var isClicked: Bool
    
    var body: some View {
        Button {
            isClicked.toggle()
        } label: {
            Text("スイッチ")
        }
    }
}

ボタンを押下するとテキストが「ON」と「OFF」に切り替わります。

重要な点は

・ContentViewからChildViewへのisClickedの受け渡し

・ChildViewでのisClickedに対する操作がContentViewのisClickedに反映

になります。

この受け渡しを担っているのがChildViewのisClickedについている@Bindingです。
これにより、ChildViewのボタンクリックでのisClickedに対する操作がContentViewのisClickedにも反映されます。

信頼できる唯一の情報源??

SSOT(Single Source of Truth)とも呼ばれる「信頼できる唯一の情報源」とは、上記のisClickedのように一元管理された情報のことを言うそうです。

よくわからないので逆を考えてみました。
上記の逆は、isClickedをContentViewとChildViewのそれぞれで管理するタイプのコードです。

struct ContentView: View {
    @State var isClicked = false
    
    var body: some View {
        VStack {
            Text(isClicked ? "ON" : "OFF")
            
            ChildView()
        }
    }
}

struct ChildView: View {
    @State private var isClicked = false
    
    var body: some View {
        Button {
            isClicked.toggle()
        } label: {
            Text("スイッチ")
        }
    }
}

ChildViewのisClickedに@Stateとprivateをつけて内部で管理するようにしました。
するとボタンを押してもテキストが変化しなくなりました。

これはContentViewのisClickedとChildViewのisClickedがそれぞれ独立したものになったためだと思われます。

このように情報を一元管理することをSSOTと呼ぶようです。

まとめ

1つの情報を他のクラスや構造体へ回すことでSSOTを守るために@Bindingが存在するようです。

ひとりごと

binding(バインディング)からingをとったbindは「縛る、むすびつける」のような意味。
binder(バインダー)は「縛るもの、結びつけるもの」ということだそうです。

これからは「御社と取引先との掛け橋になります」じゃなくて「御社と取引先のバインダーになります」でも良いということがわかりました。

どちらかというと尖りに尖った文房具卸業者に聞こえますが。。。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?