Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Structs vs Classes in Swift
Written by Team Kodeco

In Swift, classes and structures are similar in many ways but have some key differences.

Classes

  • Classes are reference types, meaning they are passed by reference when assigned to a variable or constant.
  • Classes can have a deinitializer, which is code that gets executed when an instance of the class is deallocated from memory.
  • Classes can use inheritance, allowing them to inherit properties and methods from a superclass.
  • Classes can be marked as final, which means they cannot be subclassed.

Structures

  • Structures are value types, meaning they are passed by value when assigned to a variable or constant.
  • Structures cannot have a deinitializer.
  • Structures cannot use inheritance, but can conform to protocols.
  • Structures do not need to be marked as final because they cannot be subclassed.

In general, it’s best to use a structure when the data is simple and does not need to be inherited and use a class when the data is more complex and will be inherited.

Here’s an example of when to use a class vs a struct:

class Person {
  var name: String
  var age: Int
  
  init(name: String, age: Int) {
    self.name = name
    self.age = age
  }
}

struct Grade {
  var letter: String
  var points: Double
  
  init(letter: String, points: Double) {
    self.letter = letter
    self.points = points
  }
}

In this example, a Person class is used to store data about a person, since it’ll likely have more complex behavior and methods and may be inherited in the future. A Grade struct is used to store data about a grade, since it’s a simple value and doesn’t need to be inherited.

© 2024 Kodeco Inc.