0
0
Swiftprogramming~10 mins

Why functions are first-class 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 declare a function variable that adds two numbers.

Swift
let add: (Int, Int) -> Int = [1]
Drag options to blanks, or click blank then click option'
Aadd(a: Int, b: Int) -> Int { a + b }
Bfunc add(a: Int, b: Int) -> Int { return a + b }
C{ (a, b) in a + b }
D(a, b) -> a + b
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign a function declaration instead of a closure.
Missing the 'in' keyword in the closure.
2fill in blank
medium

Complete the code to call the function stored in the variable.

Swift
let result = add[1]3, 5)
Drag options to blanks, or click blank then click option'
A<
B[
C{
D(
Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets or braces instead of parentheses.
Forgetting to include the opening parenthesis.
3fill in blank
hard

Fix the error in the function assignment by choosing the correct syntax.

Swift
let multiply: (Int, Int) -> Int = [1](a, b) in { return a * b }
Drag options to blanks, or click blank then click option'
A{
Bfunc
Clet
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'func' keyword inside a closure assignment.
Not using curly braces for closures.
4fill in blank
hard

Fill both blanks to create a function that takes another function as a parameter and calls it.

Swift
func performOperation(_ operation: (Int, Int) -> Int, _ a: Int, _ b: Int) -> Int {
    return operation[1]a, b[2]
}
Drag options to blanks, or click blank then click option'
A(
B)
C[
D]
Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets instead of parentheses.
Forgetting to close the parentheses.
5fill in blank
hard

Fill all three blanks to create a dictionary that maps strings to functions and call one of them.

Swift
let operations: [String: (Int, Int) -> Int] = [
    "add": [1],
    "subtract": [2]
]

let result = operations["add"][3](10, 5)!
Drag options to blanks, or click blank then click option'
A{ (a, b) in a + b }
B{ (a, b) in a - b }
C?
D!
Attempts:
3 left
💡 Hint
Common Mistakes
Using '?' instead of '!' to unwrap the optional.
Not using closures as dictionary values.