Search code examples
xcodeswiftarc4random

Swift 2 arch4random


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.


Solution

  • 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()