不同的班级类型

时间:2017-05-30 09:54:22

标签: swift class types switch-statement return

我正在做一个数学测验游戏。在游戏中,用户选择一个单元,然后游戏提出有关该单元练习的问题。

我所拥有的课程是:

  • 的ViewController

  • UnitSelector - 负责通知单位该用户 已选择

  • Unit01 ... to ... Unit20 - 负责随机返回一个 运动单位

还有很多练习

class UnitSelector {

      var unit: Int!

      init(unit: Int) {
        self.unit = unit
      }

      func getUnitClass() -> Any? {
        switch unit {
        case 0:
          return Unit01()
        case 1:
          return Unit02()
        // all the other cases
        case 19:
          return Unit20()
        default:
          return nil
        }
      }
    }

class GameViewController: UIViewController {

  override func viewDidLoad() {
    // more code
    unitSelector = UnitSelector(unit: selectedUnit)
    unitClass = unitSelector.getUnitClass()
    let question = unitClass.giveMeQuestion()
  }

  // all the other code
}

// all the Units are like this one
class UnitXX {
  // vars

  func giveMeQuestion() -> String {
    // code

    return "Question"
  }
}

问题是我不知道如何解决这种情况: 我把它分成单位,每个单位都有自己的练习。我将有大约20个单位,每个单位大约有5个练习。在控制器中,unitClass的类型是Any,我需要有UnitSelector.getUnitClass返回的类,Unit01()... Unit20()。 我不知道我所遵循的逻辑是否正确,所以如果有人可以帮助我......

谢谢!

1 个答案:

答案 0 :(得分:0)

你的问题对我来说并不完全清楚,但我尽力帮助: 您可以通过以下方式获取课程类型:

type(of: yourObject)

在这篇文章中提到: How do you find out the type of an object (in Swift)?

有很多(在我看来)更好的解决方案。一种是基于阵列的方法:

//questions is an array with other array inside
var questions: [[String]] =
    [
        ["Question 1 for unit type One",
         "Question 2 for unit type One",
         "Question 3 for unit type One",
         "Question N for unit type One"],

        ["Question 1 for unit type Two",
         "Question 2 for unit type Two",
         "Question 3 for unit type Two",
         "Question 4 for unit type Two",
         "Question N for unit type Two"],

        ["Question 1 for unit type N",
         "Question 2 for unit type N",
         "Question N for unit type N"]
    ]

//getting random number between 0 and the count of the questions "outter" array
var randomUnitNumber = Int(arc4random_uniform(UInt32(questions.count)))

//getting the "inner" array with questions
var questionsForUnit = questions[randomUnitNumber]

//getting random number between 0 and the count of the questions "inner" array
var randomQuestionNumber = Int(arc4random_uniform(UInt32(questionsForUnit.count)))

//getting the question
var randomQuestion = questionsForUnit[randomQuestionNumber]

//printing the question
print(randomQuestion)

我希望这会有所帮助!