0
0
Swiftprogramming~20 mins

Function declaration syntax in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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"))
Agreet(name: "Anna")
BError: Missing return statement
CHello, name!
DHello, Anna!
Attempts:
2 left
💡 Hint
Look at how the function returns a string with the name inserted.
Predict Output
intermediate
2: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))
A7
B12
C34
DError: Missing argument labels
Attempts:
2 left
💡 Hint
The function multiplies two numbers and returns the result.
Predict Output
advanced
2: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")
AWelcome, Guest!\nWelcome, Sam!
BWelcome, !\nWelcome, Sam!
CWelcome, Guest!\nWelcome, Guest!
DError: Missing argument for parameter 'name'
Attempts:
2 left
💡 Hint
Default parameters are used when no argument is provided.
Predict Output
advanced
2: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
A6
BError: Cannot pass immutable value as inout argument
C5
DError: Missing & before argument
Attempts:
2 left
💡 Hint
inout allows the function to modify the original variable.
Predict Output
expert
3: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")
}
AMin is 9, Max is 2
BMin is 3, Max is 7
CMin is 2, Max is 9
DEmpty array
Attempts:
2 left
💡 Hint
The function finds the smallest and largest numbers in the array.