1

could anyone teach me how to select an item (String) from an array by using arc4random_uniform()? I tried but I couldn't because arc4random_uniform can be used for selecting Int.

3
  • 3
    Have a look at stackoverflow.com/questions/24003191/… Commented May 17, 2015 at 16:48
  • Basically as shown in the question above, you just have to declare the random number as a Integer like so Int(randomNumber) That makes the type of your number an integer instead of a UInt32 Commented May 17, 2015 at 18:22
  • i mean how can i chage String form into Integer? Commented May 18, 2015 at 1:51

2 Answers 2

3

Swift 3 Extension

While Oisdk answer works, a extension could be more useful instead of writing that coding over and over again.

import Foundation

extension Array {

  func randomElement() -> Element  {
     if isEmpty { return nil }
     return self[Int(arc4random_uniform(UInt32(self.count)))]
  }
}

let myArray = ["dog","cat","bird"]

myArray.randomElement() //dog 
myArray.randomElement() //dog 
myArray.randomElement() //cat 
myArray.randomElement() //bird
Sign up to request clarification or add additional context in comments.

Comments

2

Subscripting an array takes and Int, but arc4random_uniform returns a UInt32. So you just need to convert between those types.

import Foundation

let array = ["ab", "cd", "ef", "gh"]

let randomItem = array[Int(arc4random_uniform(UInt32(array.count)))]

Also, arc4random_uniform gives a random number less that its argument. So just cast array.count to a UInt32, and it'll work.

1 Comment

This will crash if there are no items.

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.