-2

I would like to pass an int data from one view controller to another one.

The problem is that the int data received in the second view controller doesn't match the first view controller's int data.

View controller 1:

import UIKit
class levelsSelector: UIViewController {
    var levelSelected: Int = 0
    var gameWanted: Int = 0

    @IBAction func level1Tapped(_ sender: Any) {
        gameWanted = 1
        performSegue(withIdentifier: "gameOn", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "gameOne" {
            let levelsSelector = segue.destination as! game
            levelsSelector.finalGame = levelSelected
            let levelsSelector2 = segue.destination as! game
            levelsSelector2.finalLevel = gameWanted
        }
    }
}

View controller 2:

import UIKit
class game: UIViewController {
    var finalLevel: Int = 0
    var finalGame: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        print(finalLevel)
        print(finalGame)
    }
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70

2 Answers2

0

You've made a typo in your segue name

performSegue(withIdentifier: "gameOn", sender: self)

...

if segue.identifier == "gameOne" {

these two identifiers need to match

Simon McLoughlin
  • 8,293
  • 5
  • 32
  • 56
0
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? game {
        destination.finalGame = levelSelected 
        destination.finalLevel = gameWanted
    }

Also, check: your seque identifier on a storyboard should match a string in: perform segue method

Volodymyr
  • 1,192
  • 21
  • 42