0
0
Swiftprogramming~10 mins

Closures are reference types 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 declare a closure that adds two numbers.

Swift
let add: (Int, Int) -> Int = [1] { $0 + $1 }
Drag options to blanks, or click blank then click option'
A{
Bfunc
Cclosure
Dlambda
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'func' keyword instead of closure syntax
Trying to use 'lambda' which is not a Swift keyword
2fill in blank
medium

Complete the code to assign a closure to a variable and call it.

Swift
var multiply = [1] (Int, Int) -> Int = { $0 * $1 }
let result = multiply(3, 4)
Drag options to blanks, or click blank then click option'
Afunc
Blet
Cvar
Dclosure
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'func' keyword instead of closure type
Using 'var' incorrectly when 'let' is better here
3fill in blank
hard

Fix the error in the closure capturing a variable.

Swift
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total [1]= amount
        return total
    }
    return incrementer
}
Drag options to blanks, or click blank then click option'
A/
B-
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition
Forgetting to update total inside the closure
4fill in blank
hard

Fill both blanks to create a closure that captures and modifies a variable.

Swift
func makeCounter() -> () -> Int {
    var count = 0
    return {
        count [1]= 1
        return count [2] 0
    }
}
Drag options to blanks, or click blank then click option'
A+
B-
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition
Using wrong comparison operators
5fill in blank
hard

Fill all three blanks to create a closure that captures a string and returns its length if longer than 3.

Swift
func makeStringChecker(_ text: String) -> () -> Int? {
    return {
        let length = text.[1]
        if length [2] 3 {
            return length
        } else {
            return [3]
        }
    }
}
Drag options to blanks, or click blank then click option'
Acount
B>
Cnil
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong property name instead of count
Returning wrong value instead of nil