0
0
Swiftprogramming~10 mins

Where clauses for complex constraints 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 filter numbers greater than 10 using a where clause.

Swift
let numbers = [5, 12, 7, 20, 3]
let filtered = numbers.filter { number in
    number [1] 10
}
Drag options to blanks, or click blank then click option'
A<
B<=
C>
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > causes wrong filtering.
Using == filters only numbers equal to 10.
2fill in blank
medium

Complete the code to filter strings with length less than 5 using a where clause.

Swift
let words = ["apple", "cat", "banana", "dog"]
let shortWords = words.filter { word in
    word.count [1] 5
}
Drag options to blanks, or click blank then click option'
A<
B>=
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or >= filters longer words.
Using == filters only words with exactly 5 characters.
3fill in blank
hard

Fix the error in the where clause to filter even numbers.

Swift
let nums = [1, 2, 3, 4, 5, 6]
let evens = nums.filter { num in
    num [1] 2 == 0
}
Drag options to blanks, or click blank then click option'
A%
B/
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using / divides the number and returns a quotient, not remainder.
Using * or + does not check evenness.
4fill in blank
hard

Fill both blanks to filter words starting with 'a' and having length greater than 3.

Swift
let words = ["apple", "ant", "bat", "arc", "axe"]
let filtered = words.filter { word in
    word.hasPrefix([1]) && word.count [2] 3
}
Drag options to blanks, or click blank then click option'
A"a"
B"b"
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong prefix string filters wrong words.
Using < filters shorter words, not longer.
5fill in blank
hard

Fill all three blanks to create a dictionary of words with their lengths, filtering words longer than 4 characters.

Swift
let words = ["swift", "code", "play", "learn"]
let wordLengths = [[1]: [2] for word in words where word.count [3] 4]
Drag options to blanks, or click blank then click option'
Aword
Bword.count
C>
Dword.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.length is invalid in Swift.
Using < filters shorter words, not longer.