从数组中获取随机字符串 [英] Get Random String from an Array

查看:37
本文介绍了从数组中获取随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从数组firstArray"中获取一个随机字符串并将其打印在 UILabellabel"中.我似乎无法弄清楚,并且出现错误.感谢您的帮助.我尝试搜索,但找不到任何最新的教程/方法.

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"]
    }

推荐答案

我更喜欢使用 arc4random(),这段代码会从你的数组中随机选取项目:

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])"

这篇关于从数组中获取随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆