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

SOLVED: Day 35 - Edutainment App - Confused about values

Forums > 100 Days of SwiftUI

I am not able to understand why is actualAnswer different from the asked multiplication. I am a complete beginner to this so i appreciate your reply.

import SwiftUI
struct Questions {
    var text: String
    var question = [Int] ()
    var answer = [Int] ()
    var actualAnswer: String

  init() {
      let questionRight = Int.random(in: 1...12)
      let questionLeft = Int.random(in: 1...12)
      text = "\(questionLeft) * \(questionRight)"
      actualAnswer = "\(questionLeft * questionRight)"
  }

}
struct ContentView: View {
    var showQ = Questions().actualAnswer
    var textQ = Questions().text
//    @State private var leftQ = Questions().questionLeft
//    @State private var rightQ = Questions().questionRight

  var body: some View {
      VStack {
//            Text("\(leftQ)")
//                .padding()
//            Text("\(rightQ)")
//                .padding()
            Text("\(textQ)")
                .padding()
            Text("\(showQ)")
                .padding()
    }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2      

Because here:

    var showQ = Questions().actualAnswer
    var textQ = Questions().text

You are creating two different instances of Questions instead of using the same instance for showQ and textQ.

Questions() with the parentheses creates a Questions instance.

You should instead do something like this:

    var question = Questions()

and then in the body you can do:

            Text(question.text)
                .padding()
            Text(question.actualAnswer)
                .padding()

That way text and actualAnswer come from the same Questions instance.

3      

@roosterboy thank you a lot

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.