Get Random String from an Array [duplicate]

浪尽此生 提交于 2021-01-27 18:45:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!