
Swift Functional Programming
By :

In Swift, there are two kinds of types in terms of memory allocation: value and reference.
Value type instances keep a copy of their data. Each type has its own data and is not referenced by another variable. Structures
, enums
, and tuples
are value types; therefore, they do not share data between their instances. Assignments copy the data of an instance to the other and there is no reference counting involved. The following example presents a struct
with copying:
struct OurStruct { var data: Int = 3 } var valueA = OurStruct() var valueB = valueA // valueA is copied to valueB valueA.data = 5 // Changes valueA, not valueB print("\(valueA.data), \(valueB.data)") // prints "5, 3"
As seen from the preceding example, changing valueA.data
does not change valueB.data
.
In Swift, arrays, dictionaries, strings, and sets are all value types.
On the other hand, reference type instances share the same copy of the data. Classes and closures are reference types, so assignment...