2017-08-15 3 views
1

randomQuestionGenerator関数の外部でcurrentQuestion変数を使用する必要があります。あらかじめそれを宣言するための正しい構文は何ですか?関数外の構造体配列を持つ変数を宣言する方法

struct Questions { 
    var Question: String 
    var answer: Int 
    var answers: [String] 
} 

class GameScreen: UIViewController { 

var correctAnswer = 0 
var fullQuestions: [Questions] = [] 

func RandomQuestionGenerator(){ 
    let randomQuestion = 
Int(arc4random_uniform(UInt32(fullQuestions.count))) 
    var currentQuestion = fullQuestions[randomQuestion] 
    correctAnswer = currentQuestion.answer 
+0

あなたの 'currentQuestion'を' correctAnswer'と似ているのはなぜですか? – OOPer

答えて

1

あなたは関数の外で、オプションとしてcurrentQuestionを宣言することができます。

var currentQuestion : Questions? = nil 
func RandomQuestionGenerator() { 
    let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count))) 
    currentQuestion = fullQuestions[randomQuestion] 
    correctAnswer = currentQuestion.answer 
} 

あなたがそれを行うことができますが、より良いアプローチはリターンにこのようなランダムな質問、あなたの関数を作ることです。

func RandomQuestionGenerator() -> Questions { 
    let randomQuestion = Int(arc4random_uniform(UInt32(fullQuestions.count))) 
    return fullQuestions[randomQuestion] 
} 

これで、次のランダムな質問を取得し、必要に応じてフィールドを取得することができます。

let nextQuestion = RandomQuestionGenerator() 
print(nextQuestion.Question) 
print(nextQuestion.answers) 
+0

ランダムな質問変数を設定するだけでなく、関数はそれよりもはるかに多くの機能を持っています。 –

+0

また、質問の型として宣言しようとすると、私のView Controllerには初期化子がなく、実行されないと言われています。 –

+1

@RichardParker未割り当て状態が許可されるように、オプションである必要もあります。 – dasblinkenlight

関連する問題