2017-05-30 2 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" 
    } 
} 

問題は、私はこの状況を解決する方法を知っているドントことです: I'veは単位でそれを分割し、各ユニットは、独自の練習を持っています。私は約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)?

を持っていますその問題のための(私の意見では)より良い解決策。 1つは配列ベースのアプローチです:

//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) 

私はこれが役に立ちそうです!

関連する問題