andrw
andrw

Reputation: 810

Initializing @State variable with values from other initialized variables

I have 2 @State variables:

@State var test1:String
@State var test2:String

I can do this:

    _test1 = State(initialValue: "test1")
    _test2 = State(initialValue: "test2")

and this:

    _test1 = State(initialValue: "test1")
    _test2 = _test1

but not this:

    _test1 = State(initialValue: "test1")
    _test2 = State(initialValue: test1 + " and test2")

with the error: Variable 'self.test2' used before being initialized

What's the reasoning behind this? Is there an appropriate way to use the value in test1 as part of test2?

Upvotes: 1

Views: 329

Answers (3)

Scooter
Scooter

Reputation: 4156

Not specifically the question asked, but if you always want test2 to rely on the value of test1, then you can drop @State from one of them and use a computed property instead.

So instead of:

@State var test1: String
@State var test2: String

use:

@State var test1: String
var test2: String {
    test1 + " and test2"
}

Then just use test2 in your view anywhere that you would have used the @State property before, and when test1 changes so will test2, and the view will be redrawn as expected.

Upvotes: 0

Asperi
Asperi

Reputation: 257493

Here is tested solution. Xcode 11.4 / iOS 13.4

struct TestStatesInitialization: View {
    @State var test1:String
    @State var test2:String

    init() {
        _test1 = State(initialValue: "test1")
        _test2 = State(initialValue: _test1.wrappedValue + " and test2")
    }
    var body: some View {
        VStack {
            Text("1: \(test1)")
            Text("2: \(test2)")
        }
    }
}

Upvotes: 3

tomahh
tomahh

Reputation: 13651

The swift compiler prevents you from using any instance property before everything is initialised. A good workaround is to create a temporary variable to hold the value of test1, like so

let tempTest1 = State(initialValue: "test1")

 _test1 = tempTest1
 _test2 = State(initialValue: tempTest1.wrappedValue + " and test2")

Upvotes: 1

Related Questions