Search code examples
iosarraysswiftarc4random

Pulling random string from array with arc4random_uniform in Swift


When I run the app, I keep getting the error:

"Could not cast value of type 'Swift._NSContiguousString' to 'NSArray'." 

I've tried casting to a String as well, but that obviously wasn't the solution either. Has anyone encounter this? I'm just trying to pull a random string from the array.

firstArray = ["firstItem", "secondItem", "thirdItem"]
randomArray = firstArray[Int(arc4random_uniform(UInt32(firstArray.count)))] as! NSArray

Thanks


Solution

  • Keep your array defined as the following :

    var firstArray = ["firstItem", "secondItem", "thirdItem"]
    

    Then do the random number from here :

     let randomIndex = Int(arc4random_uniform(UInt32(firstArray.count)))
    

    Get the result like this :

    var result = self.firstArray[randomIndex]
    

    Good luck !