Swiftly

Swift 5.1 references for busy coders

Structs & classes

Structs and classes are flexible, general-purpose constructs. In Swift, structs and classes are very similar to each other, but contain important differences. Instances are created from structs and classes in similar ways.

Declaration comparison

Struct declaration

struct PlayerStruct {
  var name: String
  var level: Int

  init(name: String, level: Int) {
    self.name = name
    self.level = level
  }
}

Class declaration

class PlayerClass {
  var name: String
  var level: Int

  init(name: String, level: Int) {
    self.name = name
    self.level = level
  }
}

Usage comparison

Struct usage

let player1 = PlayerStruct(name: "Tomoko", 
                           level: 1)
print(player1) // PlayerStruct(name: "Tomoko", level: 1)
print(player1.name) // Tomoko

Class usage

let player2 = PlayerClass(name: "Isabella", 
                          level: 1)
print(player2) // main.Player
print(player2.name) // Isabella

Value types (Structs) versus reference types (Classes)

Structs are value types, like Int and String, so when a struct instance is assigned to a new variable or passed to a function, the whole instance value is copied.

In contrast, classes are reference types, so when a class instance is assigned to a new variable or passed to a function, a reference to the same existing instance is used. The instance is not actually copied.

The example below demonstrates this in practice:

struct Player {
  var name: String

  init(name: String) {
    self.name = name
  }
}

var player1 = Player(name: "Tomoko")
var player2 = player1
player2.name = "Isabella"

print(player1.name) // Tomoko
print(player2.name) // Isabella
class Player {
  var name: String

  init(name: String) {
    self.name = name
  }
}

var player1 = Player(name: "Tomoko")
var player2 = player1
player2.name = "Isabella"

print(player1.name) // Isabella
print(player2.name) // Isabella