从数组列表中打印一个没有重复项的随机字符串

时间:2017-09-04 07:58:11

标签: arrays swift xcode

基本上,我有一个数组,我希望在按下按钮时将其转移到标签。我遇到的主要问题是,我无法找到一种方法,让阵列在打印完成后不会重复某些内容

这是我的代码片段

 @IBOutlet weak var truthspot: UILabel!

@IBAction func truthclick(_ sender: Any) {

    let array = ["pasta", "boop", "test1", "test2"]
    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))

    truthspot.text = (array[randomIndex])

1 个答案:

答案 0 :(得分:0)

您应该将array移到函数之外,并在每次调用函数时删除生成的索引处的元素。

var array = ["pasta", "boop", "test1", "test2"]

@IBAction func truthclick(_ sender: Any) {
    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))

    truthspot.text = (array[randomIndex])

    array.remove(at: randomIndex)
}