Bird
0
0

What is the output of this Swift code?

medium📝 Predict Output Q13 of 15
Swift - Functions
What is the output of this Swift code?
func minMax(numbers: [Int]) -> (min: Int, max: Int) {
    var currentMin = numbers[0]
    var currentMax = numbers[0]
    for number in numbers[1...] {
        if number < currentMin { currentMin = number }
        if number > currentMax { currentMax = number }
    }
    return (currentMin, currentMax)
}

let result = minMax(numbers: [3, 7, 2, 9, 4])
print(result.min, result.max)
A2 9
B3 7
C9 2
DError: tuple elements not accessible
Step-by-Step Solution
Solution:
  1. Step 1: Trace min and max calculation

    Start with first number 3 as min and max. Iterate over 7, 2, 9, 4 updating min to 2 and max to 9.
  2. Step 2: Access tuple elements by name

    Returned tuple has named elements min and max, so result.min is 2 and result.max is 9.
  3. Final Answer:

    2 9 -> Option A
  4. Quick Check:

    min = 2, max = 9 [OK]
Quick Trick: Tuple elements accessed by name like properties [OK]
Common Mistakes:
  • Confusing min and max values
  • Trying to access tuple elements by index instead of name
  • Forgetting to start loop from second element

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes