Bird
0
0

You want to write a Swift program that safely calculates the average of an array of numbers, but the array might be empty. Which approach best uses Swift's safety features?

hard📝 Application Q15 of 15
Swift - Basics and Runtime
You want to write a Swift program that safely calculates the average of an array of numbers, but the array might be empty. Which approach best uses Swift's safety features?
AForce unwrap the array count and sum
BDivide the sum by the array count without checks
CIgnore empty arrays and return zero always
DUse optional binding to check if the array is empty before dividing
Step-by-Step Solution
Solution:
  1. Step 1: Understand the problem with empty arrays

    Dividing by zero (array count 0) causes a runtime error.
  2. Step 2: Use optional binding for safety

    Optional binding lets you check if the array has elements before dividing, avoiding errors.
  3. Step 3: Evaluate options

    Use optional binding to check if the array is empty before dividing uses Swift's safety features correctly; others risk errors or ignore safety.
  4. Final Answer:

    Use optional binding to check if the array is empty before dividing -> Option D
  5. Quick Check:

    Optional binding = safe checks [OK]
Quick Trick: Check array emptiness with optional binding before dividing [OK]
Common Mistakes:
  • Dividing without checking for zero count
  • Force unwrapping optionals causing crashes
  • Ignoring empty arrays without handling

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes