00. Structures and Classes

It will take about 5 minutes to finish reading this article.

Unlike other programming languages, In Swift, you can define a structure or class in just a single file, and the external interface to that class or structure is automatically made available for other code to use.

1. Comparing Structures and Classes.

1.1 Differences and similarities.
Structures and Classes in Swift have many things in common. Both can:

  1. Property, method and initializers can both be defined.
  2. Both support protocol and extension.

They have diferent capabilities that:

  1. Class is the reference type; Struct is a value type.
  2. Class supports inheritance; Struct does not support inheritance.
  3. The mutating keyword is not required to modify the attribute of the method declared by class; struct needs.
  4. The class does not provide a default memberwise initializer; Struct provides the default memberwise initializer.
  5. Class supports reference counting; Struct is not supported.
  6. Class supports Type casting; Struct is not supported.
  7. Class supports Deinitializers; Struct is not supported.

1.2 Identity Operators.
It can sometimes be useful to find out whether two constants or variables refer to exactly the same instance of a class. To enable this, Swift provides two identity operators:

Identical to (===)
Not identical to (!==)

Use these operators to check whether two constants or variables refer to the same single instance.

By default, custom classes and structures don’t have an implementation of the equivalence operators, known as the equal to operator (==) and not equal to operator (!=). You usually implement the == operator, and use the standard library’s default implementation of the != operator that negates the result of the == operator. For example:

1
2
3
4
5
extension Vector2D: Equatable {
static func == (left: Vector2D, right: Vector2D) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
}

2. Choosing Between Structures and Classes.

How to select Struct and Class in the project during development?

  1. Choose Structures by Default.
  2. Use Classes When You Need Objective-C Interoperability.
  3. Use Classes When You Need to Control Identity.
  4. Use Structures When You Don’t Control Identity.
  5. Use Structures and Protocols to Model Inheritance and Share Behavior.

We can make a summary that, do not use class if you can use struct.

  1. When using struct, you do not need to consider memory leaks and multi-threaded’ reads and writes, because it will copy values when passing them.
  2. Struct is stored in the stack and class is stored in the heap. Struct is more faster.

Reference

[1] Structures and Classes
[2] Choosing Between Structures and Classes
[3] Why Choose Struct Over Class?