Bird
0
0

You want to write a Swift function that accepts a variadic list of integers and returns a dictionary where keys are the integers and values are their squares. Which function correctly implements this?

hard📝 Application Q8 of 15
Swift - Functions
You want to write a Swift function that accepts a variadic list of integers and returns a dictionary where keys are the integers and values are their squares. Which function correctly implements this?
Afunc squares(_ nums: Int...) -> [Int: Int] { var dict = [Int: Int]() for n in nums { dict.append(n * n) } return dict }
Bfunc squares(nums: Int...) -> [Int: Int] { return nums.map { ($0, $0 * $0) } }
Cfunc squares(_ nums: Int...) -> [Int: Int] { return nums.reduce([:]) { $0 + [$1: $1 * $1] } }
Dfunc squares(_ nums: Int...) -> [Int: Int] { var dict = [Int: Int]() for n in nums { dict[n] = n * n } return dict }
Step-by-Step Solution
Solution:
  1. Step 1: Understand desired output

    We want a dictionary mapping each integer to its square.
  2. Step 2: Check each option

    func squares(_ nums: Int...) -> [Int: Int] { var dict = [Int: Int]() for n in nums { dict[n] = n * n } return dict } correctly creates a dictionary and assigns squares. func squares(nums: Int...) -> [Int: Int] { return nums.map { ($0, $0 * $0) } } returns an array of tuples, not a dictionary. func squares(_ nums: Int...) -> [Int: Int] { return nums.reduce([:]) { $0 + [$1: $1 * $1] } } uses invalid '+' on dictionaries. func squares(_ nums: Int...) -> [Int: Int] { var dict = [Int: Int]() for n in nums { dict.append(n * n) } return dict } tries to append to a dictionary, which is invalid.
  3. Final Answer:

    func squares(_ nums: Int...) -> [Int: Int] { var dict = [Int: Int]() for n in nums { dict[n] = n * n } return dict } -> Option D
  4. Quick Check:

    Use dictionary assignment to build key-value pairs [OK]
Quick Trick: Use dict[key] = value to build dictionary in loop [OK]
Common Mistakes:
  • Using map returns array, not dictionary
  • Trying to append to dictionary
  • Using invalid operators on dictionaries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes