Swift: How to use an Array to Randomly Select a String
If you wish to make an app that randomly selects a word or a phrase, then you’ll need to use an array. An array is a group of strings, numbers, or anything else.
Thank you for reading this post, don't forget to subscribe!
Such as:
let array = [“Heads”,”Tails”]
Since we want to randomly select a word from this array, we need to use the arc4random statement, like so:
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
Then finally we want to print the results:
print(array[randomIndex])
Now lets put the above altogether in code:
import UIKit
import Foundation
let array = [“Heads”,”Tails”]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])
About Post Author
Discover more from CompuScoop.com
Subscribe to get the latest posts sent to your email.