无法从swift中的Array中选择随机数

时间:2018-02-26 19:12:03

标签: arrays swift

我有这个代码,我想从Array1中选择一个随机元素,从Array2中选择一个随机元素,但Xcode只给出了元素的编号。

let firstNrVar = [0, 2, 4, 6, 8, 10]
let secondNrVar = [0, 2, 4, 6, 8, 10]
func numberRandomizer() {
    let shuffledFirstNr = Int(arc4random_uniform(UInt32(firstNrVar.count)))
    firstNrLbl.text = "\(shuffledFirstNr)"
    print(shuffledFirstNr)
    let shuffledSecondNr = Int(arc4random_uniform(UInt32(secondNrVar.count)))
    secondNrLbl.text = "\(shuffledSecondNr)"
    print(shuffledSecondNr)
}

1 个答案:

答案 0 :(得分:1)

你必须获得介于0和数组计数之间的随机索引,然后获取该随机索引的值,然后将该值设置为文本

func numberRandomizer() {
  let shuffledFirstIndex = Int(arc4random_uniform(UInt32(firstNrVar.count)))
  firstNrLbl.text = "\(firstNrVar[shuffledFirstIndex])"
  print("\(firstNrVar[shuffledFirstIndex])")
  let shuffledSecondIndex = Int(arc4random_uniform(UInt32(secondNrVar.count)))
  secondNrLbl.text = "\(secondNrVar[shuffledSecondIndex])"
  print("\(secondNrVar[shuffledSecondIndex])")
}