Step into Swift logo

What is a Struct?

Struct

Struct

  • Should use by default where possible.
  • Subject should be small with not much going on.
  • Use a Class if things get more complicated.
  • It’s a value type. (Post TBC - Value type vs Reference type)
  • Stored on the stack.
  • If it is a class member, it is stored on the heap.
  • Copied (Passed by value).
  • Protocol conformance.
  • Comes with a memberwise initializer (Post TBC - Memberwise initializers).
  • Extension keeps memberwise initializer (Post TBC - Extending a struct).
  • Examples: String, Array, Dict, Int.
  • Thread safe.
  • Used a lot in protocol orientated programming.
  • No dynamic memory allocation.
  • Reference counting does not apply (Post TBC - ARC).
  • Protocols allow classes, structs and enums to participate in a form of inheritance (Post TBC - Protocols).

Example:

struct Size {
  let width: Int
  let height: Int
}

Related articles:


< All Posts