Bird
0
0

Which Swift code snippet correctly declares a string and creates an independent copy of it?

easy📝 Syntax Q3 of 15
Swift - Data Types
Which Swift code snippet correctly declares a string and creates an independent copy of it?
Avar original = "Swift" var copy = original as AnyObject
Bvar original = String() var copy = &original
Clet original = "Swift" let copy = &original
Dvar original = "Swift" var copy = original
Step-by-Step Solution
Solution:
  1. Step 1: Declare a string

    Using var original = "Swift" correctly declares a mutable string.
  2. Step 2: Copy the string

    Assigning var copy = original creates a value copy because String is a value type.
  3. Step 3: Analyze other options

    Options B and C use address operators incorrectly; D tries casting to reference type which is invalid.
  4. Final Answer:

    var original = "Swift" var copy = original -> Option D
  5. Quick Check:

    Simple assignment copies string value [OK]
Quick Trick: Assigning strings copies values, no pointers needed [OK]
Common Mistakes:
  • Using & operator to copy strings
  • Casting strings to reference types incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes