Challenge - 5 Problems
Swift Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple Swift function
What is the output of this Swift code?
Swift
func greet(name: String) -> String { return "Hello, \(name)!" } print(greet(name: "Anna"))
Attempts:
2 left
💡 Hint
Look at how the function returns a string with the name inserted.
✗ Incorrect
The function greet takes a string parameter and returns a greeting with that name. The print statement outputs the returned string.
❓ Predict Output
intermediate2:00remaining
Function with multiple parameters
What does this Swift function print?
Swift
func multiply(_ a: Int, _ b: Int) -> Int { return a * b } print(multiply(3, 4))
Attempts:
2 left
💡 Hint
The function multiplies two numbers and returns the result.
✗ Incorrect
The function multiply takes two integers without argument labels and returns their product. 3 times 4 is 12.
❓ Predict Output
advanced2:00remaining
Function with default parameter values
What is the output of this Swift code?
Swift
func greet(name: String = "Guest") { print("Welcome, \(name)!") } greet() greet(name: "Sam")
Attempts:
2 left
💡 Hint
Default parameters are used when no argument is provided.
✗ Incorrect
The first call uses the default value "Guest". The second call uses the provided argument "Sam".
❓ Predict Output
advanced2:00remaining
Function with inout parameter
What is the value of x after this Swift code runs?
Swift
func increment(value: inout Int) { value += 1 } var x = 5 increment(value: &x) x
Attempts:
2 left
💡 Hint
inout allows the function to modify the original variable.
✗ Incorrect
The function increments the value by 1. Passing x with & allows the change to affect x itself.
❓ Predict Output
expert3:00remaining
Function with multiple return values using tuple
What does this Swift code print?
Swift
func minMax(numbers: [Int]) -> (min: Int, max: Int)? { guard !numbers.isEmpty else { return nil } var currentMin = numbers[0] var currentMax = numbers[0] for number in numbers[1...] { if number < currentMin { currentMin = number } else if number > currentMax { currentMax = number } } return (currentMin, currentMax) } if let result = minMax(numbers: [3, 7, 2, 9, 4]) { print("Min is \(result.min), Max is \(result.max)") } else { print("Empty array") }
Attempts:
2 left
💡 Hint
The function finds the smallest and largest numbers in the array.
✗ Incorrect
The function returns a tuple with the minimum and maximum values. The array contains 2 as smallest and 9 as largest.