LoginSignup
0
1

More than 1 year has passed since last update.

Swift Loops Cheat Sheet

Last updated at Posted at 2021-05-14

Swiftのループチットシート (日本語)

This is a cheat sheet of the loops available in Swift 5.0+

For

Since Swift 3.0, C-style for loops have been deprecated! But I include them for people who are migrating old code bases.

Loop over Ranges with For-In

Looping n times

Deprecated C-style version:

Swift_<3.0
for var i = 0; i < 10; i++ {
    print(i)
}

for-in over a closed range with the ... (closed range) operator :

Swift_>=_3.0
for i in 0...10 {
    print(i)
}

for-in over a half-open range with the ..< (half-open range) operator :

Swift_>=_3.0
for i in 0..<10 {
    print(i)
}
Looping n times in reverse

Deprecated C-style version:

Swift_<3.0
for var i = 10; i > 0; i-- {
    print(i)
}

for-in over a closed range that has been reversed using reversed():

Swift_>=_3.0
for i in (1...10).reversed() {
    print(i)
}
Looping with Stride

Deprecated C-style version:

Swift_<3.0
for var i = 0; i < 10; i += 2 {
    print(i)
}

for-in over a half-open range, stepping by the specified amount using stride(from:to:by:):

Swift_>=_3.0
for i in 0.stride(to: 10, by: 2) {
    print(i)
}

Loop over through Arrays

Looping through Array Values

Deprecated C-style version:

Swift_<3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for var i = 0; i < someNumbers.count; i++ {
    print(someNumbers[i])
}

for-in over all the values of an Array:

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for number in someNumbers {
    print(number)
}

forEach over all the values of an Array:

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
someNumbers.forEach { number in
    print(number)
}
Reverse Looping through Array Values

Deprecated C-style version:

Swift_<3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for var i = someNumbers.count - 1; i >= 0; i-- {
    print(someNumbers[i])
}

for-in over all the values of an Array that has been reversed using reversed():

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for number in someNumbers.reversed() {
    print(number)
}

forEach over all the values of an Array that has been reversed using reversed():

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
someNumbers.reversed().forEach { number in
    print(number)
}
Looping Through an Array with Index

Deprecated C-style version:

Swift_<3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for var i = 0; i < someNumbers.count; i++ {
    print("\(i + 1): \(someNumbers[i])")
}

for-in over all the indexes and values of an Array enumerated using enumerated():

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for (index, number) in someNumbers.enumerated() {
    print("\(index + 1): \(number)")
}

forEach over all the indexes and values of an Array enumerated using enumerated():

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
someNumbers.enumerated().forEach { (index, number) in
    print("\(index + 1): \(number)")
}
Looping Through Array Indices

Deprecated C-style version:

Swift_<3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for var i = 0; i < someNumbers.count; i++ {
    print(i)
}

for-in over all the indexes of an Array enumerated using indices:

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
for index in someNumbers.indices {
    print(index)
}

Looping Through a Dictionary

for-in over all the indexes and values of a Dictionary:

Swift_>=_3.0
let scores = ["Bob": 42, "Alice": 99, "Jane": 13]

for (name, score) in scores
{
    print("\(name)'s score is \(score)")
}

While

Repeats code until the condition evaluated at the start of the loop becomes false.

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
var i = 0
while(i < someNumbers.count) {
    print(someNumbers[i])
    i += 1
}

Repeat-While

Repeats code until the condition evaluated at the end of the loop becomes false.

Swift_>=_3.0
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
var i = 0
repeat {
    print(someNumbers[i])
    i += 1
} while(i < someNumbers.count)

Break

Terminates the current iteration of the loop and the flow control of the program exits the loop.

unlabeled break

Terminates the current iteration and exits the loop:

Swift
for i in 1...4{
    if i == 3 {
      break
    }
    print("i = \(i)")
  }
}

Outputs:

i = 1
i = 2 

labeled break

When using nested loops with a labeled break statement, terminates the current iteration of the labeled loop and exits the labeled loop:

Swift
outerloop: for i in 1...3{
  innerloop: for j in 1...3 {
    if j == 2 {
      break outerloop
    }
    print("i = \(i), j = \(j)")
  }
}

Outputs:

i = 1, j = 1

Continue

Skips the current iteration of the loop and the flow control of the program goes to the next iteration.

unlabeled continue

Skips the current iteration of the loop and goes to the next:

Swift
for i in 1...4{
    if i == 3 {
      continue
    }
    print("i = \(i)")
  }
}

Outputs:

i = 1
i = 2
i = 4

labeled continue

When using nested loops with a labeled continue statement, skips the current iteration of the labeled loop and goes to the next:

Swift
outerloop: for i in 1...3{
  innerloop: for j in 1...3 {
    if j == 2 {
      continue outerloop
    }
    print("i = \(i), j = \(j)")
  }
}

Outputs:

i = 1, j = 1
i = 2, j = 1
i = 3, j = 1

Higher-order functions

If you want to manipulate arrays, for instance to apply a function to each of the array elements, or to reduce the array to one result, then you should use the higher-order functions.

Array.filter(_:)

Iterates over all items in array, and return an array containing all the elements filtered by a condition.

Swift
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
let numbersUnder10 = someNumbers.filter { $0 < 10 }
print(numbersUnder10)

Array.map(_:)

Iterates over all items in array, transforming them and return an array containing the transformed elements.

Swift
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
let doubledNumbers = someNumbers.map { $0 * 2}
print(doubledNumbers)

Array.reduce(_:_:)

Iterates over all items in array, combining them together until you end up with a single value.

Swift
let someNumbers = [2, 3, 45, 6, 8, 83, 100]
let sum = someNumbers.reduce(0) { $0 + $1}
print(sum)

See also

English
Japanese
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1