how to declare an instance of a class in UIView Controller

How can I declare a variable of type GameMethod class in a subclass of UIViewController? I get compile error of "Class GameViewController has no initializers" when I add the statement: var gamemodel: GameModel. My GameModel class is stored in file GameModel.swift that is stored in same folder as GameViewController.swift.



import UIKit

class GameViewController: UIViewController {. //**compile error here

var gamemodel: GameModel

@IBAction func northButton(_ sender: UIButton) {

gamemodel.move(direction: .north)

}

When you add a stored property (gamemodel) to your GameViewController class, you need to either provide a default value for that property/variable or set the value in your init methods.


default value

var gamemodel = GameModel()

or

var gamemodel: GameModel? = nil


initializer

var gamemodel: GameModel

init(model: GameModel)
{
   super.init()
   gamemodel = model
}

Just an example... you would need to call UIViewController's correct initializer instead of just init().

how to declare an instance of a class in UIView Controller
 
 
Q