DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 6/100)

Swift

  • for loop
  • while loop
  • tuples
  • loop through array and dictionary
  • loop with labels

Use for loop to loop through array

let names = ["John", "Doe"]
for name in names {
    print(name)
}
Enter fullscreen mode Exit fullscreen mode

Use counter:

for i in 0..<names.count {
    print(names[i])
}
Enter fullscreen mode Exit fullscreen mode

... is inclusive:

for i in 0...5 {
    print(i)
} // 0, 1, 2, 3, 4, 5
Enter fullscreen mode Exit fullscreen mode

Tuples in swift

Tuples allow you to create and pass around groupings of values. You can use tuples to return multiple values from a function as a single compound value.

However, tuples in Swift are not designed to be iterated over like collections such as arrays or dictionaries. They do not conform to the Sequence protocol, which is what enables the use of for-in loops in Swift. A tuple is meant to hold a fixed number of elements, each potentially of a different type, and you access each element individually using index numbers starting from zero or by naming the elements.

Here is an example of how to define and access elements in a tuple:

// Define a tuple with three elements
let person = ("John", 30, 5.10)

// Access elements by their index
let name = person.0
let age = person.1
let height = person.2

// You can also use named elements in a tuple
let personNamed = (name: "John", age: 30, height: 5.10)

// Access elements by their name
let nameNamed = personNamed.name
let ageNamed = personNamed.age
let heightNamed = personNamed.height
Enter fullscreen mode Exit fullscreen mode

If you’d like to perform an action on each element of a tuple, you can’t use a standard for loop. Instead, you’d have to manually write the action for each element:

print("Name: \(personNamed.name)")
print("Age: \(personNamed.age)")
print("Height: \(personNamed.height)")
Enter fullscreen mode Exit fullscreen mode

For tuples with a large number of elements, if you find yourself needing to iterate over them, it might be a sign that you should use a different data structure, such as an array or a struct, which more appropriately suit collections that require iteration.

While loop

var roll = 0
while roll != 20 {
    // roll a new dice and print what it was
    roll = Int.random(in: 1...20)
    print("I rolled a \(roll)")
}
Enter fullscreen mode Exit fullscreen mode

Loop with labels

outerLoop: for i in 1...3 {
    innerLoop: for j in 1...3 {
        if i == 2 && j == 2 {
            print("Breaking out of the innerLoop when i=\(i) and j=\(j)")
            break innerLoop
        }

        // Continue to the next iteration of outerLoop if a specific condition is met
        if i == 3 && j == 1 {
            print("Continuing outerLoop when i=\(i) and j=\(j)")
            continue outerLoop
        }

        print("Running i=\(i) and j=\(j)")
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example:

  • outerLoop and innerLoop are labels that have been applied to the outer and inner for loops, respectively.
  • When if i == 2 && j == 2 condition is met, the break innerLoop statement exits the inner loop only and continues with the next iteration of the outer loop.
  • When if i == 3 && j == 1 condition is met, the continue outerLoop statement skips to the next iteration of the outer loop, essentially restarting the innerLoop

Loop through dictionary

let myDictionary = ["key1": "value1", "key2": "value2", "key3": "value3"]

for (key, value) in myDictionary {
    print("The key is \(key) and the value is \(value)")
}
Enter fullscreen mode Exit fullscreen mode

In this example, the myDictionary variable is a dictionary with String keys and String values. The for-in loop iterates over each key-value pair in the dictionary, and during each iteration, the key and value variables are assigned to the current key and value.

You can also loop through the keys or values alone by using the .keys or .values properties:

Loop through just keys:

for key in myDictionary.keys {
    print("The key is \(key)")
}
Enter fullscreen mode Exit fullscreen mode

Loop through just values:

for value in myDictionary.values {
    print("The value is \(value)")
}
Enter fullscreen mode Exit fullscreen mode

If you need the index during iteration, you can use the enumerated() method. However, since dictionaries are unordered collections, the index in this case does not indicate a position within the dictionary but simply the iteration count:

for (index, (key, value)) in myDictionary.enumerated() {
    print("Item \(index): \(key) = \(value)")
}
Enter fullscreen mode Exit fullscreen mode

Checkpoint

  • If it’s a multiple of 3, print “Fizz”
  • If it’s a multiple of 5, print “Buzz”
  • If it’s a multiple of 3 and 5, print “FizzBuzz”
  • Otherwise, just print the number.
for i in 1...100 {
    if i.isMultiple(of: 3) && i.isMultiple(of: 5) {
        print("\(i): FizzBuzz")
    } else if i.isMultiple(of: 3) {
        print("\(i): Fizz")
    } else if i.isMultiple(of: 5) {
        print("\(i): Buzz")
    } else {
        print("\(i): \(i)")
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)