0
0
Swiftprogramming~10 mins

Why closures are fundamental in Swift - Test Your Understanding

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

Complete the code to define a simple closure that adds two numbers.

Swift
let add = { (a: Int, b: Int) -> Int in return a [1] b }
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' will subtract instead of add.
2fill in blank
medium

Complete the code to call the closure with arguments 3 and 5.

Swift
let result = add([1])
Drag options to blanks, or click blank then click option'
A(3, 5)
B3, 5
C3 5
D[3, 5]
Attempts:
3 left
💡 Hint
Common Mistakes
Passing arguments without parentheses or commas causes syntax errors.
3fill in blank
hard

Fix the error in the closure that captures a variable and increments it.

Swift
var count = 0
let increment = { count [1] 1 }
Drag options to blanks, or click blank then click option'
A-=
B++
C+=
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '++' causes a syntax error in Swift 3 and later.
4fill in blank
hard

Fill both blanks to create a closure that filters even numbers from an array.

Swift
let numbers = [1, 2, 3, 4, 5]
let evens = numbers.filter { $0 [1] [2] 2 == 0 }
Drag options to blanks, or click blank then click option'
A%
B==
C!=
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' will select odd numbers instead.
5fill in blank
hard

Fill all three blanks to create a closure that maps strings to their lengths if length is greater than 3.

Swift
let words = ["apple", "cat", "banana"]
let filteredLengths = words.reduce(into: [:]) { dict, word in
    if word.count [1] [2] {
        dict[[3]] = word.count
    }
}
Drag options to blanks, or click blank then click option'
A>
B3
Cword
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' will filter the wrong words.