0
0
Swiftprogramming~20 mins

Why functions are first-class in Swift - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of function assigned to a variable

What is the output of this Swift code?

Swift
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

let greeter = greet
print(greeter("Alice"))
AError: Cannot assign function to variable
Bgreet
CHello, greeter!
DHello, Alice!
Attempts:
2 left
💡 Hint

Remember, in Swift, functions can be assigned to variables and called through them.

🧠 Conceptual
intermediate
1:30remaining
Why can Swift functions be passed as arguments?

Why can Swift functions be passed as arguments to other functions?

ABecause Swift automatically converts functions to strings when passed as arguments.
BBecause functions are treated as values and can be stored in variables or passed around.
CBecause functions are only allowed as global variables in Swift.
DBecause Swift does not support passing functions as arguments.
Attempts:
2 left
💡 Hint

Think about what it means for functions to be 'first-class'.

🔧 Debug
advanced
2:30remaining
Identify the error when returning a function

What error does this Swift code produce?

Swift
func makeIncrementer() -> (Int) -> Int {
    func addOne(number: Int) -> Int {
        return number + 1
    }
    return addOne
}
AError: Cannot call function when returning, should return function itself
BNo error, returns a function correctly
CError: Missing return type for inner function
DError: addOne is not defined
Attempts:
2 left
💡 Hint

Look carefully at what is returned: the function call or the function itself?

📝 Syntax
advanced
1:30remaining
Correct syntax for function type variable

Which option correctly declares a variable that holds a function taking an Int and returning a String?

Avar converter: (Int) -> String
Bvar converter: (Int) => String
Cvar converter: Int -> String
Dvar converter = Int -> String
Attempts:
2 left
💡 Hint

Remember the syntax for function types in Swift uses parentheses and arrow.

🚀 Application
expert
3:00remaining
Using functions as first-class citizens to sort an array

Given this Swift code, which option correctly sorts the array numbers in descending order using a function passed as an argument?

Swift
let numbers = [3, 1, 4, 2]

func descending(_ a: Int, _ b: Int) -> Bool {
    return a > b
}

let sortedNumbers = numbers.sorted(by: ???)
print(sortedNumbers)
A{ a, b in a < b }
Bdescending()
Cdescending
Dnumbers.descending
Attempts:
2 left
💡 Hint

When passing a function as an argument, do you call it or just pass its name?