0
0
Swiftprogramming~20 mins

For-in loop with collections in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift For-in Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a for-in loop over an array
What is the output of this Swift code?
let numbers = [1, 2, 3, 4]
var result = 0
for num in numbers {
    result += num
}
print(result)
Swift
let numbers = [1, 2, 3, 4]
var result = 0
for num in numbers {
    result += num
}
print(result)
A1234
B24
C10
DError: Cannot add Int to Int
Attempts:
2 left
💡 Hint
Think about what adding all numbers in the array means.
Predict Output
intermediate
2:00remaining
Iterating over a dictionary with for-in
What will this Swift code print?
let dict = ["a": 1, "b": 2, "c": 3]
var keys = ""
for key in dict.keys {
    keys += key
}
print(keys)
Swift
let dict = ["a": 1, "b": 2, "c": 3]
var keys = ""
for key in dict.keys {
    keys += key
}
print(keys)
A"cba"
BAny permutation of "abc"
C"abc"
DError: Cannot iterate over dict.keys
Attempts:
2 left
💡 Hint
Dictionary keys are iterated in insertion order since Swift 5.0.
🔧 Debug
advanced
2:00remaining
Identify the error in for-in loop over a set
What error does this Swift code produce?
let fruits: Set = ["apple", "banana", "cherry"]
for fruit in fruits {
    print(fruit.uppercased())
}
Swift
let fruits: Set = ["apple", "banana", "cherry"]
for fruit in fruits {
    print(fruit.uppercased())
}
ANo error; prints uppercase fruit names in any order
BError: Cannot iterate over a Set
CRuntime error: fruit is nil
DError: 'uppercased()' is not a method on String
Attempts:
2 left
💡 Hint
Sets can be iterated like arrays.
Predict Output
advanced
2:00remaining
Output of nested for-in loops with arrays
What is the output of this Swift code?
let arr1 = [1, 2]
let arr2 = ["a", "b"]
var output = ""
for num in arr1 {
    for letter in arr2 {
        output += "\(num)\(letter) "
    }
}
print(output)
Swift
let arr1 = [1, 2]
let arr2 = ["a", "b"]
var output = ""
for num in arr1 {
    for letter in arr2 {
        output += "\(num)\(letter) "
    }
}
print(output)
A"1a 1b 2a 2b "
B"a1 b1 a2 b2 "
C"1a 2a 1b 2b "
D"Error: Cannot concatenate Int and String"
Attempts:
2 left
💡 Hint
The outer loop runs first, then the inner loop fully for each outer item.
📝 Syntax
expert
2:00remaining
Which option causes a syntax error in for-in loop?
Which of these Swift for-in loops will cause a syntax error?
let items = ["x", "y", "z"]
Swift
let items = ["x", "y", "z"]
Afor item in items { print(item) }
B
for item in items {
print(item)
}
C
}
)meti(tnirp
{ smeti ni meti rof
Dfor item in items print(item)
Attempts:
2 left
💡 Hint
Swift requires braces {} for the body of for-in loops.