Zeefum Dajma
Zeefum Dajma

Reputation: 63

Declare a variable without type

I am making a game and I have different game modes. These game modes are in separate classes. When the user picks a game mode, the respective class is used in the code. However, for the manipulation of any game mode I have used scene. Is there a way to use one variable or do I have to use multiple?

Here is the ViewController that deals with the game modes:

class GameViewController: UIViewController {

let classic = GameScene(fileNamed: "GameScene")
let timed = Timed(fileNamed: "Timed")
let endless = Endless(fileNamed: "Endless")
var scene: SKScene?

init() {
    if (gameMode == "Classic"){
        var scene = classic
        print("Classic")
    }
    else if (gameMode == "Timed"){
        var scene = timed
        print("Timed")

    }
    else if (gameMode == "Endless"){
        var scene = endless
        print("Endless")

    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destination as? Postgame {
        yourVC.score = scene!.score
    }
}

Upvotes: 1

Views: 5116

Answers (2)

Hexfire
Hexfire

Reputation: 6058

Theoretically speaking, you can go with:

var score: Any!

Any means anything, any type.

Other than that, it seems that you're looking for (and basically talking about) a Strategy design pattern. It seems to be the right way to solve your task. In short: define a protocol, implement it by all your strategies, use the one you need, call methods by protocol-unified names.

Have a read: Strategy Design Pattern in Swift

Upvotes: 4

Ssswift
Ssswift

Reputation: 1027

A Swift variable has to have a type. Otherwise, how would the compiler know what you can do with it?

In this case, it apparently has a score property, so you should make a protocol with that:

protocol GameMode {
    var score: Int { get }
    // and whatever else is common to these classes
}

Upvotes: -1

Related Questions