1

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.

luk2302
  • 55,258
  • 23
  • 97
  • 137
Roduck Nickes
  • 1,021
  • 2
  • 15
  • 41

1 Answers1

0

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()
luk2302
  • 55,258
  • 23
  • 97
  • 137
  • Can i have a function with the whole array, and another function that only shows the first 3 names in the array? – Roduck Nickes Dec 25 '15 at 20:19
  • @RoduckNickes don't know what you mean – luk2302 Dec 25 '15 at 20:51
  • Nvm.. Do i put the whole first code and the second code in a button action? – Roduck Nickes Dec 25 '15 at 20:52
  • @RoduckNickes no, put the variables and the function in the class / on class level and the line for assigning the `text` into the button action – luk2302 Dec 25 '15 at 20:52
  • What am i supposed to do about this: http://s15.postimg.org/6o882c7nf/Screen_Shot_2015_12_25_at_22_02_00.png ? – Roduck Nickes Dec 25 '15 at 21:02
  • @RoduckNickes put `var originalNames = [String]()` instead of `let originalNames = names` and put `originalNames = names` in the `viewDidLoad` – luk2302 Dec 25 '15 at 21:03
  • You are a lifesaver, thanks! Is there any other ways i can do this, because i also have an array with over 400 strings that has long sentence with up to 50 characters long, and that will use a lot of space in my .swift file. – Roduck Nickes Dec 25 '15 at 21:07
  • @RoduckNickes well, you can try putting it into a file and reading that file, but that is entirely different topic, if you tried around with it you can of course ask a new question on SO. – luk2302 Dec 25 '15 at 21:08