2015-04-22 4 views
-1

У меня есть приложение для викторины. Он часто выявляет все вопросы. Как я могу заставить их отображаться только один раз, и поэтому после последнего вопроса появится сообщение?Викторина показывает те же вопросы

func nextText(){ 
     let randomNumber = Int(arc4random_uniform(4)) 
     var textLabel = "" as NSString 
     switch (randomNumber){ 
     case 1: 
      textLabel = "Question1." 
      break 
     case 2: 
      textLabel = "Question2." 
      break 
     case 3: 
      textLabel = "Question3." 
      break 
     case 4: 
      textLabel = "Question4." 
      break 
     default: 
      textLabel = "Question 5" 
     } 
     self.textLabel.text = textLabel as? String 
    } 
} 

ответ

0

Просто поместите внутрь корпуса по-разному:

func nextText(){ 
     let randomNumber = Int(arc4random_uniform(4)) 
     var textLabel = "" as NSString 
     switch (randomNumber){ 
     case 1: 
      textLabel = "Question1." 
      self.textLabel.text = textLabel as? String 
      break 
     case 2: 
      textLabel = "Question2." 
      self.textLabel.text = textLabel as? String 
      break 
     case 3: 
      textLabel = "Question3." 
      self.textLabel.text = textLabel as? String 
      break 
     case 4: 
      textLabel = "Question4." 
      self.textLabel.text = textLabel as? String 
      break 
     default: 
      textLabel = "Question 5" 
      self.textLabel.text = textLabel as? String 
     } 
    } 
+0

Все, что вы сделали, когда вы устанавливаете 'textLabel.text' изменения, этот код имеет точно такой же результат, как код в вопросе. – ABakerSmith

+0

@ABakerSmith Я получаю все разные. –

+0

Я думаю, что вопрос требует, чтобы вопросы не повторялись. Если я не понял. – ABakerSmith

0

Может быть, вы могли бы хранить вопросы, как массив. Затем был создан новый массив смешанных вопросов. Затем пройдите через массив, представляющий вопросы пользователю. Как только вы дойдете до последнего вопроса в массиве, вы можете отобразить всплывающее сообщение. Вот пример:

1. Перемешать массив из How do I shuffle an array in Swift?

extension Array { 
    func shuffled() -> [T] { 
     var list = self 
     for i in 0..<(list.count - 1) { 
      let j = Int(arc4random_uniform(UInt32(list.count - i))) + i 
      swap(&list[i], &list[j]) 
     } 
     return list 
    } 
} 

2. Ваши вопросы:

let questions = ["Question1", "Question2", "Question3", "Question4"] 
let shuffledQuestions = questions.shuffled() 

3. Перечислите через ваши перемешиваются вопросы:

var questionIndex = 0 

for question in shuffledQuestions { 
    // Present the question to the user 
    self.textLabel.text = question 
    questionIndex++ 
} 

4. Как только пользователь достиг последнего вопроса, появится всплывающее окно. Например. когда questionIndex == shuffledQuestions.count

0

Определить изменяемый массив. Добавить randomNumber в массив. Проверить randomNumber существует в массиве. Если его существует, воспроизводите случайное число.

Это ваш вопрос цели - с:

//Defining an array 
@property NSMutableArray *asked; 


-(void) nextText{ 
//This will generate a random number between 1 and 5. 
int randomNumber = arc4random() % 5+1; 

NSString * textLabel =nil; 

//This will check all questions are asked 
if ([asked count] ==5) { 
    self.myLabel.text = @"All questions completed"; 
    return; 
} 

//This will check is random number asked 
if ([asked containsObject:[NSString stringWithFormat:@"%i",randomNumber]]) { 
    return; 
} 

//This will add random number to asked questions and will ask the question of random number 
else{ 
    [asked addObject:[NSString stringWithFormat:@"%i",randomNumber]]; 
    switch (randomNumber){ 
     case 1: 
      textLabel = @"Question1."; 
      break; 
     case 2: 
      textLabel = @"Question2."; 
      break; 
     case 3: 
      textLabel = @"Question3."; 
      break; 
     case 4: 
      textLabel = @"Question4."; 
      break; 
     case 5: 
      textLabel = @"Question5."; 
      break; 
    } 
    self.myLabel.text = textLabel; 
    } 
} 

//If you want more than limited question, create and fill question array 
//After you can ask like this. Change else part with this 
else{ 
    [asked addObject:[NSString stringWithFormat:@"%i",randomNumber]]; 
    self.myLabel.text = [questions objectAtIndex:randomNumber]; 
    } 
+0

Проблема с этим подходом заключается в том, что вы добавляете больше числа в свой массив, вероятность выбора числа, которое еще не было выбрано, уменьшается. Это не проблема, когда есть только пять вопросов. Но если бы было еще много, это могло бы занять довольно долгое время, чтобы создать порядок для вопросов. – ABakerSmith

+0

Если вы не хотите задавать только 5 вопросов, вы можете создать еще один массив для вопросов. И приведите часть переключателя в петлю. Вроде: // Это добавит случайное число в заданные вопросы и задаст вопрос о случайном числе else { [ask addObject: [NSString stringWithFormat: @ "% i", randomNumber]]; self.myLabel.text = [вопросы objectAtIndex: randomNumber]; } – kordiseps

0

Почему вы не просто поставить вопросы в массиве и поп из него каждый раз, когда вы показываете вопрос? Так что вы можете сделать что-то вроде этого:

var questions = ["Question1", "Question2", "Question3", "Question4", "Question5"] 

for var i = questions.count; i > 0; { 
    let randomNumber = Int(arc4random_uniform(UInt32(--i))) 
    let textLabel = questions[randomNumber] as String 
    println(textLabel) 
    questions.removeAtIndex(randomNumber) 
} 

if questions.count == 0 { 
    println("should show the popup") 
}