This is a memo for Learn Swift HK Meetup, which written on Oct in 2020.
Please let me know in the comments what I have misunderstood.
TL;DR,
Reference Types and Value Types in Swift
A. Reference Types and Value Types in Swift
Pure Swift language doesn’t have the “Pointer” concept like C or C++ have.
But Swift Data Types has two categories. There are Reference Types and Value Types.
Reference Types Data
- Reference Types are purely only Class and Closure.
- Functions are included in Closure.
- All objects defined by the Class or Closure are Reference Types
Value Types Data
- All but the Reference Types
- Typical examples are Struct and Enum.
- String, Array, Data…, every Swift basic Type is defined as Struct.
B. Pass By Reference and Pass By Value
1. Pass By Reference
When an instance of Reference Types is assigned to a variable or constant, a reference to that instance is passed to the variable or constant.
2. Pass By Value
When an instance of Value Types is assigned to a variable or constant, a copy of that instance is created and passed to the variable or constant.
3. Copy-on-write
If you know the C language, you can understand it like passing the pointer. But strictly speaking, Swift uses the “Copy-on-write” technique. It is the purpose of reducing memory usage.
https://en.wikipedia.org/wiki/Copy-on-write
C. Swift, Python, Go Comparison
1. Swift Array is also Value Types
In Swift, “Array” is defined as Value Type too.
2. Python List sample.
For example, Python “List” is defined as a Reference Type.
3. Go List and Slice sample.
For example, Go lang “List” and “Slice”. In Go, “List” is defined as Value Type. But “Slice” is defined as Reference Type. And Go programmer, usually use “Slice”, because “Slice” is easier to use compare to “List”.
4. Swift Array Sample
In Swift Array is Value Type. That’s why in the following code, between these 2 lists don’t affect each other.
D. Swift Class and Struct
How about Class and Struct in Swift?
1. Struct
Please execute the above code. In the above script, there are 2 structs and instances. These instances are looked like independently exist.
2. Class
Because Class is Reference Types, in the above code, both “someClassInstance” and “copyClassInstance” are affected by each other.
3. Struct with Class
How about Struct which has Class inside?
In the following case, 1 Struct has 1 “intValue” and 1 Class which has 1 “Value”.
In the above case, “intValue” is as Value Types. But “Value” inside Class is as Reference Types.