简体   繁体   English

声明一个没有类型的变量

[英]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:这是处理游戏模式的 ViewController:

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
    }
}

Theoretically speaking, you can go with:从理论上讲,您可以使用:

var score: Any!

Any means anything, any type. Any意味着任何东西,任何类型。

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阅读: Swift 中的策略设计模式

A Swift variable has to have a type. Swift 变量必须有一个类型。 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:在这种情况下,它显然有一个score属性,所以你应该用它来制定一个协议:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM