Learn SwiftUI (Day 6/100)
Tags: swift
Published: 2024-05-01 02:14:13

## Swift

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

### Use for loop to loop through array

```swift
let names = ["John", "Doe"]
for name in names {
	print(name)
}
```

Use counter:
```swift
for i in 0..<names.count {
	print(names[i])
}
```

`...` is inclusive:
```swift
for i in 0...5 {
	print(i)
} // 0, 1, 2, 3, 4, 5
```

### 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:

```swift
// 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
```

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:

```swift
print("Name: \(personNamed.name)")
print("Age: \(personNamed.age)")
print("Height: \(personNamed.height)")
```

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

```swift
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)")
}
```

### Loop with labels

```swift
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)")
    }
}

```
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

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

for (key, value) in myDictionary {
    print("The key is \(key) and the value is \(value)")
}
```

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:

```swift
for key in myDictionary.keys {
    print("The key is \(key)")
}
```

Loop through just values:

```swift
for value in myDictionary.values {
    print("The value is \(value)")
}
```

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:

```swift
for (index, (key, value)) in myDictionary.enumerated() {
    print("Item \(index): \(key) = \(value)")
}
```

## 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.

```swift
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)")
	}
}
```