0
0
Swiftprogramming~20 mins

Functions as types in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code using function types?
Consider the following Swift code. What will it print when run?
Swift
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

let operation: (Int, Int) -> Int = add
print(operation(3, 4))
A7
B34
CError: Cannot assign function to variable
D0
Attempts:
2 left
💡 Hint
Remember that the variable 'operation' holds a function that adds two numbers.
🧠 Conceptual
intermediate
1:30remaining
What is the type of this Swift function variable?
Given the declaration: let transform: (String) -> Int, what does this type mean?
AA function that takes a String and returns an Int
BA function that takes an Int and returns a String
CA variable holding a String value
DA function that takes no parameters and returns nothing
Attempts:
2 left
💡 Hint
Look at the arrow (->) in the type declaration.
🔧 Debug
advanced
2:30remaining
Why does this Swift code cause a compile error?
Examine the code below and choose the reason it fails to compile.
Swift
func multiply(_ x: Int, _ y: Int) -> Int {
    return x * y
}

let operation: (Int) -> Int = multiply
print(operation(5))
AMissing return statement in 'multiply' function
BType mismatch: 'multiply' expects two Ints but 'operation' expects one Int
CCannot assign a function to a constant
DFunction 'multiply' is not defined
Attempts:
2 left
💡 Hint
Check the number of parameters expected by the function and the variable.
🚀 Application
advanced
3:00remaining
Which option correctly uses a function type as a parameter?
You want to write a Swift function 'applyTwice' that takes a function from Int to Int and an Int, then applies the function twice. Which code correctly defines 'applyTwice'?
A
func applyTwice(_ f: (Int, Int) -> Int, _ x: Int) -> Int {
    return f(x, x)
}
B
func applyTwice(f: Int, x: Int) -> Int {
    return f + x
}
C
func applyTwice(_ f: (Int) -> Int, _ x: Int) -> Int {
    return f(f(x))
}
D
func applyTwice(_ f: Int, _ x: Int) -> Int {
    return f * x
}
Attempts:
2 left
💡 Hint
The parameter 'f' should be a function that takes one Int and returns an Int.
Predict Output
expert
3:00remaining
What is the output of this Swift code using nested function types?
Analyze the code and select the output it produces.
Swift
func makeAdder(_ x: Int) -> (Int) -> Int {
    func adder(_ y: Int) -> Int {
        return x + y
    }
    return adder
}

let addFive = makeAdder(5)
print(addFive(10))
AError: Cannot return nested function
B510
C5
D15
Attempts:
2 left
💡 Hint
The function 'makeAdder' returns a function that adds 'x' to its input.