Discover why choosing structs or classes can save your app from hidden bugs and confusion!
Structs vs classes in iOS Swift - When to Use Which
Imagine you are building a contact list app. You try to keep track of each contact's details manually by copying and updating information everywhere in your code.
When you change a contact's phone number, you must find and update every place that holds that contact's data.
This manual way is slow and confusing. You might forget to update some places, causing wrong or outdated info to show.
It's easy to make mistakes and hard to keep your app working well as it grows.
Using structs and classes helps organize your data smartly. Structs make copies of data, so changes don't affect others unexpectedly.
Classes let you share data easily by reference, so updates happen everywhere automatically.
This clear difference helps you choose the right tool to keep your app's data safe and easy to manage.
var contact1 = ["name": "Alice", "phone": "123"] var contact2 = contact1 contact2["phone"] = "456" // manual copy, easy to mess up
struct Contact {
var name: String
var phone: String
}
var contact1 = Contact(name: "Alice", phone: "123")
var contact2 = contact1
contact2.phone = "456" // struct copy, safe and clearIt enables you to manage data safely and clearly, avoiding bugs and making your app easier to build and maintain.
Think of a photo editing app: using classes for shared filters means changing a filter updates all photos using it, while using structs for individual photo settings keeps each photo's edits separate.
Manual data copying is error-prone and hard to maintain.
Structs create safe copies of data; classes share data by reference.
Choosing between structs and classes helps keep your app's data organized and bug-free.
Practice
struct and class in Swift?Solution
Step 1: Understand value vs reference types
In Swift,structis a value type, meaning it is copied when assigned or passed around.classis a reference type, meaning instances share the same reference.Step 2: Evaluate each option
structis a value type andclassis a reference type. correctly states the difference.structsupports inheritance butclassdoes not. is wrong becausestructdoes not support inheritance.classis copied on assignment butstructis shared. reverses the behavior.structcan only have stored properties,classcannot. is false becauseclasscan have stored properties.Final Answer:
structis a value type andclassis a reference type. -> Option BQuick Check:
Value type = struct, Reference type = class [OK]
- Confusing value and reference types
- Thinking structs support inheritance
- Assuming classes are copied on assignment
Solution
Step 1: Recall Swift struct syntax
A struct is declared with the keywordstruct, followed by the name and curly braces containing properties.Step 2: Check each option
struct Person { var name: String } matches the correct syntax:struct Person { var name: String }. class Person { var name: String } usesclass, not struct. struct Person = { var name: String } uses an invalid assignment syntax. struct Person: String { var name } incorrectly tries to inherit fromStringand misses type forname.Final Answer:
struct Person { var name: String } -> Option DQuick Check:
Struct declaration usesstruct Name { }[OK]
- Using class keyword instead of struct
- Incorrect syntax with equals sign
- Missing type annotation for properties
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 5
print(p1.x)What will be printed?
Solution
Step 1: Understand struct copying behavior
SincePointis a struct (value type), assigningp1top2copies the data. They are independent.Step 2: Analyze mutation and print
Changingp2.xto 5 does not affectp1.x. Sop1.xremains 1. The print statement outputs 1.Final Answer:
1 -> Option AQuick Check:
Structs copy on assignment, so original stays unchanged [OK]
- Assuming p1.x changes when p2.x changes
- Confusing structs with classes (reference types)
- Expecting runtime error on mutation
struct Counter {
var count: Int
}
func increment(counter: Counter) {
counter.count += 1
}What is the main reason for the error?
Solution
Step 1: Understand function parameter mutability
In Swift, function parameters are constants by default. You cannot modify them inside the function.Step 2: Analyze the error cause
The parametercounteris a struct instance passed by value but immutable inside the function. Trying to changecounter.countcauses a compile error.Final Answer:
Function parameter 'counter' is a constant by default -> Option AQuick Check:
Function parameters are immutable unless markedinout[OK]
- Thinking structs can't have mutable properties
- Believing '+=' is invalid for Int
- Assuming classes are required for mutation
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
}
}Solution
Step 1: Identify sharing vs copying needs
If you want updates to reflect everywhere (shared state), you need a reference type.Step 2: Match type to behavior
classis a reference type, so instances are shared.structcopies data, so changes won't reflect across copies.Final Answer:
Useclassbecause it shares references and updates reflect everywhere. -> Option CQuick Check:
Shared mutable state = class [OK]
- Choosing struct when shared updates are needed
- Thinking classes can't have initializers
- Believing structs can't have properties
Ready to prove it?
Pass the test and this pattern moves unknown
