Structs and classes help you organize data and behavior in your app. They let you create your own types to keep your code clean and easy to understand.
Structs vs classes in iOS Swift
struct MyStruct {
var property: Int
func method() {
// code
}
}
class MyClass {
var property: Int
func method() {
// code
}
}Structs use the keyword struct, classes use class.
Structs are value types, classes are reference types.
p2.x does not affect p1.x because structs are copied.struct Point {
var x: Int
var y: Int
}
let p1 = Point(x: 10, y: 20)
var p2 = p1
p2.x = 30person2.name also changes person1.name because classes share the same instance.class Person { var name: String init(name: String) { self.name = name } } let person1 = Person(name: "Alice") let person2 = person1 person2.name = "Bob"
This example shows that Garage is a class (reference type), so garage1 and garage2 share the same instance. Changing garage2.car.model affects garage1.car.model. But Car is a struct (value type), so the car inside the class is not copied when assigned; both garages share the same car instance.
struct Car {
var model: String
}
class Garage {
var car: Car
init(car: Car) {
self.car = car
}
}
var car1 = Car(model: "Toyota")
var garage1 = Garage(car: car1)
var garage2 = garage1
garage2.car.model = "Honda"
print("garage1 car model: \(garage1.car.model)")
print("garage2 car model: \(garage2.car.model)")Use structs for simple data that you want to copy when assigned or passed around.
Use classes when you need shared, mutable state or inheritance.
Structs come with automatic memberwise initializers, classes do not.
Structs are value types and copied on assignment.
Classes are reference types and shared on assignment.
Choose based on whether you want copying or shared behavior.
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
