LoginSignup
21
8

More than 3 years have passed since last update.

【SwiftUI】@Bindingや@Stateをつけたプロパティをイニシャライザで初期化する

Posted at

Error: 'self' used before all stored properties are initialized

こんな感じで素直にイニシャライザを定義してしまうと、上記のエラーが発生します。

WrappedTextField.swift
struct WrappedTextField: View {
    private var placeholder: String?
    @Binding private var textContent: String

    init(placeholder: String? = nil, textContent: String) {
        self.placeholder = placeholder
        self.textContent = textContent
        // Swift Compiler Error
        // 'self' used before all stored properties are initialized
        // Return from initializer without initializing all stored properties
    }

    var body: some View {
        TextField(placeholder ?? "", text: $textContent)
            .multilineTextAlignment(.center)
    }
}

解決方法

Property Wrapperをつけたプロパティを初期化するには、暗黙的に定義される_textContent: Binding<String>を使用する必要があります。

@Binding private var textContent: String

init(placeholder: String? = nil, textContent: Binding<String>) {
    self.placeholder = placeholder
    self._textContent = textContent
}

イニシャライザを自分で定義しなければ、呼び出し側では自動的に引数の型がBindingとなるため、Property Wrapperのことを意識しなくても使えるのですが、カスタムのイニシャライザを用意する場合は、Property Wrapperについて知っておかないといけません。

参考

Property Wrapper 入門

21
8
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
21
8