2017-05-30 51 views
0

我正在製作一個數學問答遊戲。在遊戲中,用戶選擇一個單位,然後遊戲提出有關本單元練習的問題。不同課程類型

的類我已經是:

  • 的ViewController

  • UnitSelector - 負責通知用戶 已經選擇

  • Unit01單位...到... 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()。 我不知道如果我遵循的邏輯是正確的,所以如果有人可以幫助我...

謝謝!

+0

也許在'Unit'中引入閉包屬性'exercice'並在初始化時設置它。 – shallowThought

回答

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) 

我希望這會對您有所幫助!