0
0
Swiftprogramming~10 mins

For-in loop with collections in Swift - Interactive Code Practice

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

Complete the code to loop through all elements in the array and print each one.

Swift
let fruits = ["Apple", "Banana", "Cherry"]
for [1] in fruits {
    print([1])
}
Drag options to blanks, or click blank then click option'
Aindex
Bfruit
Citem
Dfruits
Attempts:
3 left
💡 Hint
Common Mistakes
Using the collection name instead of a variable for each element.
Using a variable name that suggests an index instead of an element.
2fill in blank
medium

Complete the code to loop through the dictionary and print each key and value.

Swift
let ages = ["Alice": 25, "Bob": 30, "Charlie": 35]
for ([1], age) in ages {
    print("\([1]) is \(age) years old")
}
Drag options to blanks, or click blank then click option'
Akey
Bage
Cname
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using the value variable name for the key.
Using a variable name that does not represent keys.
3fill in blank
hard

Fix the error in the code to correctly loop through the set and print each element.

Swift
let colors: Set = ["Red", "Green", "Blue"]
for [1] in colors {
    print([1])
}
Drag options to blanks, or click blank then click option'
Aindex
Bcolors
Ccolor
Ditem
Attempts:
3 left
💡 Hint
Common Mistakes
Using the collection name instead of a single element variable.
Using a variable name that implies an index which sets do not have.
4fill in blank
hard

Fill both blanks to create a dictionary that maps each word to its length if the length is greater than 3 using reduce.

Swift
let words = ["cat", "house", "dog", "elephant"]
let lengths = words.reduce(into: [String: Int]()) { result, [1] in
    if [2] > 3 {
        result[[1]] = [2]
    }
}
Drag options to blanks, or click blank then click option'
Aword
Bword.count
Cword.length
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word.length' which is not valid in Swift.
Using 'count' alone without specifying the variable.
5fill in blank
hard

Fill all three blanks to create a for-in loop that prints each index and element from the array.

Swift
let animals = ["dog", "cat", "bird"]
for ([1], [2]) in animals.[3]() {
    print("Index \([1]): \([2])")
}
Drag options to blanks, or click blank then click option'
Aindex
Belement
Cenumerated
Ditems
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'items()' which is not a valid method.
Swapping index and element variable names.