Gonzo Loopback
Gonzo Loopback

Reputation: 17

SWIFT IF ELSE and Modulo

In Swift, I need to create a simple for-condition-increment loop with all the multiples of 3 from 3-100. So far I have:

var multiplesOfThree: [String] = []

for var counter = 0; counter < 30; ++counter {

    multiplesOfThree.append("0")



    if counter == 3 {

        multiplesOfThree.append("3")

    } else if counter == 6 {

        multiplesOfThree.append("6")

    } else if counter == 9 {

        multiplesOfThree.append("9")

    }



    println("Adding \(multiplesOfThree[counter]) to the Array.")

}

I would like to replace all the if and else if statements with something like: if (index %3 == 0)

but I’m not sure what the proper syntax would be? Also, if I have a single IF statement do I need a .append line to add to the Array?

Upvotes: 0

Views: 6371

Answers (1)

drewag
drewag

Reputation: 94753

You are very much on the right track. A few notes:

  1. Swift provides a more concise way to iterate over a fixed number of integers using the ..< operator (an open range operator).
  2. Your if statement with the modulus operator is exactly correct
  3. To make a string from an Int you can use \(expression) inside a string. This is called String Interpolation

Here is the working code:

var multiplesOfThree: [String] = []

for test in 0..<100 {
    if (test % 3 == 0) {
        multiplesOfThree.append("\(test)")
    }
}

However, there is no reason to iterate over every number. You can simply continue to add 3 until you reach your max:

var multiplesOfThree: [String] = []
var multiple = 0
while multiple < 100 {
    multiplesOfThree.append("\(multiple)")
    multiple += 3
}

As rickster pointed out in the comments, you can also do this in a more concise way using a Strided Range with the by method:

var multiplesOfThree: [String] = []

for multiple in stride(from: 0, to: 100, by: 3) {
    multiplesOfThree.append("\(multiple)")
}

Getting even more advanced, you can use the map function to do this all in one line. The map method lets you apply a transform on every element in an array:

let multiplesOfThree = Array(map(stride(from: 0, to: 100, by: 3), { "\($0)" }))

Note: To understand this final code, you will need to understand the syntax around closures well.

Upvotes: 6

Related Questions