Swift Review — Structures and Classes

kyrie-eleison
1 min readMar 11, 2021

How are structures and classes different in Swift?

source: https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html

  1. Comparison

They both have: properties, methods, subscript syntax, initialization, can be extended(using extension syntax), protocols to follow

But only classes have: inheritance, typecasting, deinitialization, and reference counting

So, it seems that classes have much more complex structures and functionalities, and as it is, Swift Docs prefers structures and enums to classes. We use classes when it is appropriate.

2. initialization

Although a lot of details would be discussed in the Initialization part, here we will talk a little bit about the initialization of structures and classes.

Structures have by default what is called “memberwise initializer”: if you declare a bunch of properties of a structure without initialization(no init function, of course), Swift asks those properties’ initial values when the structure gets its instances.

3. Structures are value types(and enums as well!)

Value types are types that are copied whenever they are assigned to variables, constants, or arguments of functions. Data types such as Int, String, Bool are all implemented as structures so that they are copied as they pass around the codes. For the sake of optimization, collection types(Array, Dictionary, etc.) are only copied before modifications.

4. Classes are reference types

Contrary to value types, reference types are not copied but share the same instance object(so only the names are different). For this reason, there exist identity operators which you might have seen in JavaScript, to identify class instances.

--

--