NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: How to run a property initialiser before self is available

Forums > Swift

I am not sure how to sort this error out and cannot see how to apply other answers to this:

struct HomeView: View {
    @ObservedObject var savedVariables = SavedVariables()

    @State private var number1 = 0
    @State private var number2 = 0
    @State private var givenAnswer = ""
    @State private var comparableAnswer = Int(givenAnswer) ?? 0

    var body: some View {
        VStack{
        Text("What is:")
            Text("\(number1) x \(number2)")
            Section{
                TextField("Enter Answer", text: $givenAnswer)
            }
        }
    }

    func NewSum(){
        number1 = Int.random(in: 0...12)
        number2 = Int.random(in: 0...12)
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView(savedVariables: SavedVariables())
    }
}

1      

From Day 23: Views as properties:

Swift does not let us make one stored property that depends on another stored property However, you can make computed properties

You didn't list your class in your code, so I made one up.

class SavedVariables: ObservableObject {
    @Published var someVariable: String = ""
}

struct HomeView: View {
    @ObservedObject var savedVariables = SavedVariables()

    @State private var number1 = 0
    @State private var number2 = 0
    @State private var givenAnswer = ""

    var comparableAnswer: Int {
        Int(givenAnswer) ?? 0
    }

    var body: some View {
        VStack{
        Text("What is:")
            Text("\(number1) x \(number2)")
            Section{
                TextField("Enter Answer", text: $givenAnswer)
            }
        }
    }

    func NewSum(){
        number1 = Int.random(in: 0...12)
        number2 = Int.random(in: 0...12)
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView(savedVariables: SavedVariables())
    }
}

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.