问题
I am trying to get a random string from array "firstArray" and print it in UILabel "label". I cannot seem to figure it out and I get errors. Your help is appreciated. I tried searching but could not find any up-to-date tutorials/methods.
import UIKit
class ViewController: UIViewController {
@IBOutlet var label: UILabel!
@IBAction func random(_ sender: Any) {
let firstArray = [ "hi" , "bye" , "hello"]
}
回答1:
I'd rather using arc4random(), this code will pick up random items from your array:
let firstArray = ["hi", "bye", "hello"]
let randomItem = Int(arc4random() % UInt32(firstArray.count))
myLabel.text = "\(firstArray[randomItem])"
回答2:
You have to generate random numbers between 0 and your array count, then set the label text to the corresponding item in array, like this:
@IBAction func random(_ sender: UIButton) {
let firstArray = [ "hi" , "bye" , "hello"]
var randomNumber = Int(arc4random_uniform(UInt32(firstArray.count)))
randLabel.text = firstArray[randomNumber]
}
this thread is helpful to understand the random logic.
来源:https://stackoverflow.com/questions/41256456/get-random-string-from-an-array