UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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())
    }
}

3      

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())
    }
}

3      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.