What is the output of this Swift code?
func greet(name: String) -> String { return "Hello, \(name)!" } let greeter = greet print(greeter("Alice"))
Remember, in Swift, functions can be assigned to variables and called through them.
The function greet is assigned to the variable greeter. Calling greeter("Alice") runs the original function, producing "Hello, Alice!".
Why can Swift functions be passed as arguments to other functions?
Think about what it means for functions to be 'first-class'.
Functions in Swift are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions just like any other value.
What error does this Swift code produce?
func makeIncrementer() -> (Int) -> Int { func addOne(number: Int) -> Int { return number + 1 } return addOne }
Look carefully at what is returned: the function call or the function itself?
The code tries to return addOne(), which calls the function and returns an Int. The return type expects a function (Int) -> Int, so it should return addOne without parentheses.
Which option correctly declares a variable that holds a function taking an Int and returning a String?
Remember the syntax for function types in Swift uses parentheses and arrow.
The correct syntax for a function type variable is var name: (InputType) -> ReturnType. Option A follows this.
Given this Swift code, which option correctly sorts the array numbers in descending order using a function passed as an argument?
let numbers = [3, 1, 4, 2] func descending(_ a: Int, _ b: Int) -> Bool { return a > b } let sortedNumbers = numbers.sorted(by: ???) print(sortedNumbers)
When passing a function as an argument, do you call it or just pass its name?
The sorted(by:) method expects a function of type (Int, Int) -> Bool. Passing descending (without parentheses) passes the function itself. Using descending() calls the function and passes its result, which is incorrect.