0

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....
3
  • 1
    Array<Int>. Also, the language is not suited for deaf programmers - it's called Swift, and not SWIFT. Commented Oct 30, 2014 at 9:52
  • 1
    Why don't you just keep the result in any array? Commented Oct 30, 2014 at 9:52
  • @AnthonyKong Please can you explain what I should do? Commented Oct 30, 2014 at 9:53

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

So array[0] will give the first random number, array[1] will give the second?
Yes. Array uses 0-based indexing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.