0
0
iOS Swiftmobile~5 mins

Structs vs classes in iOS Swift

Choose your learning style9 modes available
Introduction

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.

When you want to group related data together, like a point with x and y coordinates.
When you need to create reusable blueprints for objects in your app, like a user profile.
When you want to decide if your data should be copied or shared when used in different places.
When you want to use simple data containers without inheritance.
When you want to use features like inheritance or reference sharing.
Syntax
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.

Examples
Changing p2.x does not affect p1.x because structs are copied.
iOS Swift
struct Point {
  var x: Int
  var y: Int
}

let p1 = Point(x: 10, y: 20)
var p2 = p1
p2.x = 30
Changing person2.name also changes person1.name because classes share the same instance.
iOS Swift
class Person {
  var name: String
  init(name: String) {
    self.name = name
  }
}

let person1 = Person(name: "Alice")
let person2 = person1
person2.name = "Bob"
Sample App

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.

iOS Swift
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)")
OutputSuccess
Important Notes

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.

Summary

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.