Arthur Macpherson Arthur Macpherson - 1 month ago 4
iOS Question

Change variable and send it to second view controller

I am creating a shop screen for my game. Where you can buy character for example. I need a variable to change when a button is pressed on the shop view and then for it to be sent to the next view controller. The second view controller will then select the correct player based on the value of the variable i have the following code for the shop view controller:

import Foundation
import UIKit

class Shop: UIViewController {

@IBAction func buttonPressed(_ sender: AnyObject){
var x = 1
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "segue") {
let dest = segue.destination as! GameViewController
dest.x = x
}
}
}


But the variable is not global so how do i do it. Any advice would be much appreciated.

Answer

Based on your requirements I believe a global Singleton object is your best option.

A global singleton will allow you to access your shop data across controllers.

E.g.

class ShopManager {
    static let sharedInstance = ShopManager()

    static var x = 0 // some initial value

    private init() {} //Ensures singleton is unique
} 

Now you can get/set ShopManager.x (or any other variables/objects declared in the singleton class) anywhere without having to pass data between controllers.

import Foundation
import UIKit

class Shop: UIViewController {

    @IBAction func buttonPressed(_ sender: AnyObject){
        ShopManager.x = 1
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "segue") {
            let dest = segue.destination as! GameViewController
            //no need to set dest.x here. just access ShopManager.x from the destination controller!
        }
    }
}

class ShopManager {
    static let sharedInstance = ShopManager()

    static var x = 0 // some initial value

    private init() {} //Ensures singleton is unique
}