Search code examples
iosvariablesfor-loopswiftarc4random

Swift - Create variables with different names in a for loop


I am learning Apple Swift with the hope of releasing apps for the iPhone.

There are three different 'modes' to my game: 5 swipes, 10 swipes, or 25 swipes. Let's use 5 swipes as an example. I want a variable to be assigned to each swipe, which will be a random integer within the range 1...100 (inclusive). Obviously it doesn't seem neat when I am creating variables in a long list like this:

var s1 = arc4random_uniform...
var s2 = arc4random_uniform...

Also that could just be a pain when I get to 25 swipes.

So I thought, maybe I could use a 'for' loop. So:

for index(in 1...5) {
//create variable with different name with a random integer
}

So here's where my problem lies... I am unsure how I would create variables with different names. So: s1, s2, s3, s4, and s5.

It would probably be in the form of an algorithm like:

var s(prevnumber+1) = arc4random_uniform....

Solution

  • I will do it this way:

    var numElement = 5 // change to 10 or 25 depends on what you need
    
    var array = Array<UInt32>(count: numElement, repeatedValue: 0)
    
    
    for i in 0 ..< numElement {
        array[i] = arc4random_uniform(100)
    }
    

    Then to access the first variable, you can do

     array[0]
    

    And it will give you the random number