Swift 2 arch4random [duplicate]

不打扰是莪最后的温柔 提交于 2019-12-11 11:45:42

问题


In my application, I use something like this to get random text on my label, except in my main let randomNumbercode, in xCode, it has over 300 cases, to much to paste in here.:

let randomNumber = Int(arc4random_uniform(23))
var textLabel = "" as NSString
switch (randomNumber){
case 1:
    textLabel = "Kim."
    break
case 2:
    textLabel = "Phil."
    break
case 3:
    textLabel = "Tom"
    break
case 4:
    textLabel = "Jeff"
    break
default:
    textLabel = "Austin"
}
self.randomLabel.text = textLabel as String

But the problem is, that sometimes it shows the same text on the label 5-6 times, and other cases is not even used yet, because it choose randomly. So how can I choose randomly, but if case example case 1 is already shown, it wont show up again, until all other cases has been shown.


回答1:


Have an array of Names instead of a gigantic switch case:

var names = ["Kim.", "Phil.", "Tom", "Jeff", "Austin"] // and all your remaining names
let originalNames = names

func getRandomName() -> String {
    if (names.count == 0) {
        names = originalNames
    }
    let randomNumber = Int(arc4random_uniform(UInt32(names.count)))
    return names.removeAtIndex(randomNumber)
}

This ensures every name gets printed before starting from the beginning again. The sample output is:

Tom, Kim., Austin, Phil., Jeff

and then it starts again

Austin, Jeff, Phil. ...

Finally put something like the following wherever it fits your need:

self.randomLabel.text = getRandomName()


来源:https://stackoverflow.com/questions/34465960/swift-2-arch4random

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