Bird
0
0

Given an array of integers, how can you create a dictionary where keys are the integers and values are their squares?

hard📝 Application Q8 of 15
iOS Swift - Swift Language Essentials
Given an array of integers, how can you create a dictionary where keys are the integers and values are their squares?
AUse a Set to store squares and convert to dictionary
BUse array.reduce to sum all squares
CUse array.filter to keep only squared numbers
DUse Dictionary(uniqueKeysWithValues:) with map to pair each number with its square
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary creation from array

    Dictionary(uniqueKeysWithValues:) creates dictionary from key-value pairs.
  2. Step 2: Use map to create pairs of number and its square

    Map each number to (number, number*number) tuple.
  3. Final Answer:

    Use Dictionary(uniqueKeysWithValues:) with map to pair each number with its square -> Option D
  4. Quick Check:

    Map array to key-value pairs for dictionary [OK]
Quick Trick: Map array to (key, value) tuples then build dictionary [OK]
Common Mistakes:
  • Using Set which loses keys
  • Filtering instead of mapping
  • Reducing to sum instead of dictionary

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes