Bird
0
0

What is wrong with this Swift code snippet?

medium📝 Debug Q6 of 15
Swift - Collections
What is wrong with this Swift code snippet?
var colors: Set = ["red", "green", "blue"]
colors.add("yellow")
AThe method 'add' does not exist for Set; use 'insert' instead.
BSets cannot contain string elements.
CYou cannot declare a Set with var, it must be let.
DThe Set must be initialized with parentheses, not brackets.
Step-by-Step Solution
Solution:
  1. Step 1: Identify the method used

    The code uses 'add' to insert an element into a Set.
  2. Step 2: Check Swift Set API

    Swift's Set type uses 'insert' to add elements, not 'add'.
  3. Final Answer:

    'add' is not a valid method; use 'insert' instead. -> Option A
  4. Quick Check:

    Check Set methods in Swift documentation [OK]
Quick Trick: Use 'insert' to add elements to a Set in Swift [OK]
Common Mistakes:
  • Using 'add' instead of 'insert' to add elements to a Set
  • Assuming Sets cannot be mutable with var
  • Confusing array and Set initialization syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes