O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Value versus reference types

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required