iComputerfreak
iComputerfreak

Reputation: 1011

Difference between SwiftUI State initializers

When initializing an @State variable, there are two initializers:

/// Initialize with the provided initial value.
public init(wrappedValue value: Value)

/// Initialize with the provided initial value.
public init(initialValue value: Value)

Is there a difference between the two initializers or are they doing the same? Is one of them preferred to use when creating a new @State variable?

Upvotes: 13

Views: 1192

Answers (2)

foolbear
foolbear

Reputation: 964

You don’t call this initializer(init(wrappedValue:)) directly. Instead, declare a property with the @State attribute, and provide an initial value; for example, @State private var isPlaying: Bool = false.

FYI: https://developer.apple.com/documentation/swiftui/state/3365450-init

We using init(initialValue:) to Creates the state with an initial value.

For example:

struct TestView3: View {
    @ObservedObject var data = TestData.shared
    @State private var sheetShowing = false
    var body: some View {
        print("test view3 body, glabel selected = \(data.selected)"); return
        VStack {
            Text("Global").foregroundColor(data.selected ? .red : .gray).onTapGesture {
                self.data.selected.toggle()
            }.padding()
            Button(action: {
                self.sheetShowing = true
                print("test view3, will show test view4")
            }) { Text("Show TestView4") }.padding()
        }.sheet(isPresented: $sheetShowing) { TestView4(selected: self.data.selected) }
    }
}

struct TestView4: View {
    @ObservedObject var data = TestData.shared
    @State private var selected = false
    init(selected: Bool) {
        self._selected = State(initialValue: selected)   // <-------- here
        print("test view4 init, glabel selected = \(data.selected), local selected = \(self.selected)")
    }
    var body: some View {
        print("test view4 body, glabel selected = \(data.selected), local selected = \(selected)"); return
        VStack {
            Text("Local").foregroundColor(selected ? .red : .gray).onTapGesture {
                self.selected.toggle()
                print("test view4, local toggle")
            }.padding()
            Text("Global").foregroundColor(data.selected ? .red : .gray).onTapGesture {
                self.data.selected.toggle()
                print("test view4, global toggle")
            }.padding()
        }
    }
}

Upvotes: -2

iComputerfreak
iComputerfreak

Reputation: 1011

According to the swift-evolution proposal:

init(initialValue:) has been renamed to init(wrappedValue:) to match the name of the property.

As of Swift 5.1 both are available and none is marked as deprecated. I still would recommend using init(wrappedValue:).

Upvotes: 11

Related Questions