What is the difference between struct, class, and actor?

1.1.2 · L2 · Interview

Reported at: Meta

Predict first

Does this compile?

final class Player { var name = "A" }

let p = Player()
p.name = "B"
  • Yes
  • No — p is a let

Mental model. Struct = a photocopy. Class = a shared document. Actor = a shared document with a doorman who lets one person in at a time.

Struct — value semantics, no inheritance, members must be mutating to change self, no deinit.

Class — reference semantics, inheritance, deinit, identity via ===, participates in Objective-C runtime.

Actor — a reference type whose mutable state is isolated. Calls from outside must await and hop to the actor's executor, so only one task mutates its state at a time.

All three can conform to protocols. Actors do not support inheritance, and they are reference types — a fact people forget because they feel value-like at the call site.

For a class, let freezes the reference, not the object. With a struct, the same code would be an error.

structclassactor
Semanticsvaluereferencereference
Inheritancenoyesno
deinitnoyesyes
Identity (===)noyesyes
Mutating selfneeds mutatingfreeinside the actor only
Outside callssyncsyncawait (isolated)
Data-race safetyby copyingyour jobby isolation

Common traps

  • “Actors are value types.” No — they are reference types with isolated state. Passing an actor around shares the same instance.
  • “Actors eliminate all data races.” They protect their own isolated state. Data leaked out of an actor, or captured by reference, is still racy.

They might follow up with

  • Does an actor have deinit? Yes — actors are reference types and may have a deinit, though it is nonisolated.
  • Can an actor conform to a protocol with synchronous requirements? Only if the requirement is nonisolated, or the conformance is isolated to the actor.

Related questions

  • 1.1.1 What is the difference between a value type and a reference type in Swift? When do you choose each?
  • 1.1.4 When would you still use a class in a Swift-first codebase?

← What is the difference between a value type and a reference type in…   Where do value types live — stack or heap? →