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.