Challenge - 5 Problems
Swift Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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))
Attempts:
2 left
💡 Hint
Remember that the variable 'operation' holds a function that adds two numbers.
✗ Incorrect
The variable 'operation' is assigned the function 'add' which sums two integers. Calling operation(3, 4) returns 7.
🧠 Conceptual
intermediate1:30remaining
What is the type of this Swift function variable?
Given the declaration: let transform: (String) -> Int, what does this type mean?
Attempts:
2 left
💡 Hint
Look at the arrow (->) in the type declaration.
✗ Incorrect
The type (String) -> Int means a function that accepts a String input and returns an Int output.
🔧 Debug
advanced2: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))
Attempts:
2 left
💡 Hint
Check the number of parameters expected by the function and the variable.
✗ Incorrect
The variable 'operation' expects a function taking one Int, but 'multiply' requires two Ints, causing a type mismatch.
🚀 Application
advanced3: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'?
Attempts:
2 left
💡 Hint
The parameter 'f' should be a function that takes one Int and returns an Int.
✗ Incorrect
Option C correctly defines 'applyTwice' taking a function (Int) -> Int and applies it twice to 'x'. Other options have wrong parameter types or logic.
❓ Predict Output
expert3: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))
Attempts:
2 left
💡 Hint
The function 'makeAdder' returns a function that adds 'x' to its input.
✗ Incorrect
The function 'makeAdder' returns 'adder' which adds 'x' (5) to its argument (10), so output is 15.