Could you clarify what you want ?
- You have 3 buttons
- you define a random rightAnswerPlace
- you want the button at this position to have the firstSign
- what do you want for the other 2 ? sign2 and sign3 randomly ?
Could you also explain what view is ?
struct Sign {
var name: String = ""
}
let firstSign = Sign(name: "first") // Why would it be optional ?
let secondSign = Sign(name: "second")
let thirdSign = Sign(name: "third")
var buttons: [UIButton] = [UIButton(frame: CGRect(x: 20, y: 50, width: 80, height: 20)),
UIButton(frame: CGRect(x: 120, y: 50, width: 80, height: 20)),
UIButton(frame: CGRect(x: 220, y: 50, width: 80, height: 20))
]
// You will have to add buttons as subviews
var rightAnswerPlace = (0...2).randomElement()!
buttons[rightAnswerPlace].setTitle(firstSign.name, for: .normal)
var remainingPlaces = [0, 1, 2]
remainingPlaces.remove(at: rightAnswerPlace)
let secondSignPlace = remainingPlaces.randomElement()!
for i in remainingPlaces { // Let us set the others
if i == secondSignPlace {
buttons[i].setTitle(secondSign.name, for: .normal)
} else {
buttons[i].setTitle(thirdSign.name, for: .normal)
}
}
- A more direct way to do it is to order the signs randomly. That will allocate "first" at a random position:
struct Sign {
var name: String = ""
}
let firstSign = Sign(name: "first") // Why would it be optional ?
let secondSign = Sign(name: "second")
let thirdSign = Sign(name: "third")
var signs = [firstSign, secondSign, thirdSign]
var buttons: [UIButton] = [UIButton(frame: CGRect(x: 20, y: 50, width: 80, height: 20)),
UIButton(frame: CGRect(x: 120, y: 50, width: 80, height: 20)),
UIButton(frame: CGRect(x: 220, y: 50, width: 80, height: 20))
]
// You will have to add buttons as subviews
signs.shuffle() // That puts signs in random order
// And now, assign buttons titles with signs in random order. first will ba at a random position (see after how to find this position)
for (i, button) in buttons.enumerated() {
button.setTitle(signs[i].name, for: .normal)
}
let rightAnswerPlace = signs.firstIndex(where: { $0.name == "first" })
print("rightAnswer is", rightAnswerPlace!)
for i in 0...2 {
print(buttons[i].title(for: .normal)!)
}