0

I have this code and I want to pick a random element from Array1 and a random element from Array2 but Xcode is only giving me the number of the element.

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)
}
4
  • Am I understanding you correctly, you're trying to access the array's value? This would be as easy as let firstValue = firstNrVar[shuffledFirstNr] Your label would then be set via firstNrLbl.text = "\(firstValue)" Currently, you're only getting a random index, not the array's value at that index. Commented Feb 26, 2018 at 19:16
  • No, I want it to pick up randomly an element from the Array {firstNrVar}, and another random element from the Array {secondNrVar}. That's mean the number must be 0, 2, 4, 6, 8 or 10, but xCode is counting where the number is and printing it out. Commented Feb 26, 2018 at 19:20
  • Yup, that's what I thought. With your current code, you are generating a random index, which you can use to access an array's value at that index. That you could do as mentioned above. Commented Feb 26, 2018 at 19:23
  • Xcode is only giving... Xcode has nothing to do with it -- it's your code. Commented Feb 26, 2018 at 19:37

2 Answers 2

1

you have to get the random index between 0 and array count and then get the value at that random index and then set that value to the text

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])")
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just get the values using the number of the element.

let value = firstNrVar[shuffledFirstNr]
firstNrLbl.text = "\(value)"

let secondValue = secondNrVar[shuffledSecondNr]
secondNrLbl.text = "\(secondValue)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.