Reputation: 91
i have really no idea, how to shuffled answers. I have colletion of buttons (buttonA, buttonB, buttonC) and var answers
let answer = [
["30","20","10"],
["cat", "dog", "butterfly"],
["flower", "sun", "tree"]
]
for i in 0..<buttons.count{
answer[i].shuffled(using: &RandomNumberGenerator)
buttons[i].setTitle(self.answer[self.numberOfQuestion][i], for: .normal) //this row is ok
}
this answers i must put into each button, but not in the same position. The correct answer is always in the first position, so in this moment is every correct answer in buttonA.
error 1 : Type 'RandomNumberGenerator.Protocol' cannot conform to 'RandomNumberGenerator'; only struct/enum/class types can conform to protocols
error 2:Cannot pass immutable value of type 'RandomNumberGenerator.Protocol' as inout argument
I have never used shuffled before. Sorry for this primitive question, but i am begginer in swift. Thanks
Upvotes: 0
Views: 118
Reputation: 437622
The RandomNumberGenerator
is a protocol, but you wouldn’t use that, literally, as a parameter, but rather might supply a object that conformed to that protocol.
But you really don’t need to worry about that. Just use shuffled
(or randomElement
) directly, without supplying a random number generator. If you’re just trying to shuffle each of these three subarrays, you might do:
let answers = [
["30","20","10"],
["cat", "dog", "butterfly"],
["flower", "sun", "tree"]
].map { $0.shuffled() }
That would yield things like:
[
["20", "10", "30"],
["dog", "cat", "butterfly"],
["tree", "sun", "flower"]
]
Then you could do things like:
for (index, button) in buttons.enumerated() {
button.setTitle(answers[numberOfQuestion][index], for: .normal)
}
Note, we have moved the shuffle before we get to our loop of buttons, as that will ensure that answers are not repeated. But if you want to allow for answers to repeat, you might not shuffle at all, but just grab a random element:
let answers = [
["30", "20", "10"],
["cat", "dog", "butterfly"],
["flower", "sun", "tree"]
]
for button in buttons {
button.setTitle(answers[numberOfQuestion].randomElement(), for: .normal)
}
Upvotes: 3
Reputation: 46
let buttons = [UIButton(), UIButton(), UIButton()]
let answers = [
["30","20","10"],
["cat", "dog", "butterfly"],
["flower", "sun", "tree"]
]
let shuffledAnswers = answers.map { $0.shuffled() }
buttons.enumerated().forEach {
let answer = shuffledAnswers[$0.offset].first
$0.element.setTitle(answer, for: .normal)
}
Upvotes: 2