0
0
Swiftprogramming~10 mins

Why Swift loops are safe by default - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a safe loop that iterates over an array.

Swift
let numbers = [1, 2, 3, 4, 5]
for number in [1] {
    print(number)
}
Drag options to blanks, or click blank then click option'
Anumbers
B0..<5
C1...5
DArray(1...5)
Attempts:
3 left
💡 Hint
Common Mistakes
Using a range instead of the array variable causes errors or unexpected behavior.
2fill in blank
medium

Complete the code to safely iterate over the indices of an array.

Swift
let fruits = ["Apple", "Banana", "Cherry"]
for index in [1] {
    print(fruits[index])
}
Drag options to blanks, or click blank then click option'
A1...fruits.count
B0..<fruits.count
C0...fruits.count
D1..<fruits.count
Attempts:
3 left
💡 Hint
Common Mistakes
Using a closed range causes an index out of range error.
3fill in blank
hard

Fix the error in the loop to prevent out-of-bounds access.

Swift
let letters = ["a", "b", "c"]
for i in 0...[1] {
    print(letters[i])
}
Drag options to blanks, or click blank then click option'
Aletters.count - 1
Bletters.count - 2
Cletters.count + 1
Dletters.count
Attempts:
3 left
💡 Hint
Common Mistakes
Using letters.count causes a runtime error due to invalid index.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that filters keys with values greater than 10.

Swift
let data = ["a": 5, "b": 15, "c": 20]
let filtered = data.filter { $0.[1] > [2] }
Drag options to blanks, or click blank then click option'
Avalue
B10
Ckey
D15
Attempts:
3 left
💡 Hint
Common Mistakes
Using $0.key instead of $0.value causes wrong filtering.
5fill in blank
hard

Fill all three blanks to create a safe loop that prints uppercase keys with values less than 50.

Swift
let scores = ["math": 45, "science": 55, "english": 40]
for ([1], [2]) in scores {
    if [3] < 50 {
        print([1].uppercased())
    }
}
Drag options to blanks, or click blank then click option'
Asubject
Bscore
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing variable names or using incorrect comparisons causes errors.