Bird
0
0

You want to create a Swift type to represent a user profile that can be shared and updated across your app without copying. Which should you choose and why?

hard📝 Application Q15 of 15
iOS Swift - Swift Language Essentials
You want to create a Swift type to represent a user profile that can be shared and updated across your app without copying. Which should you choose and why?
struct UserProfile {
  var name: String
  var age: Int
}

class UserProfileClass {
  var name: String
  var age: Int
  init(name: String, age: Int) {
    self.name = name
    self.age = age
  }
}
AUse <code>struct</code> because it copies data and prevents accidental changes.
BUse <code>class</code> because structs cannot have properties.
CUse <code>class</code> because it shares references and updates reflect everywhere.
DUse <code>struct</code> because classes cannot have initializers.
Step-by-Step Solution
Solution:
  1. Step 1: Identify sharing vs copying needs

    If you want updates to reflect everywhere (shared state), you need a reference type.
  2. Step 2: Match type to behavior

    class is a reference type, so instances are shared. struct copies data, so changes won't reflect across copies.
  3. Final Answer:

    Use class because it shares references and updates reflect everywhere. -> Option C
  4. Quick Check:

    Shared mutable state = class [OK]
Quick Trick: Choose class for shared mutable data, struct for copies [OK]
Common Mistakes:
  • Choosing struct when shared updates are needed
  • Thinking classes can't have initializers
  • Believing structs can't have properties

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes