Difference between Value type and Reference type in Swift

A value type is a type where the data or value  is copied when assigned to a constant , variable or when it is passed to some other function. Many basic data types in Swift are of Value type. For example: Arrays, Dictionaries, Collections,Structures, Enumerations, Strings. In value type, the data is actually stored in the memory allotted for the variable or constant.For each instance, the value stored in the variable is copied.The newly copied value is independent of previous value.

[ Value types hold the value directly.Reference types hold the address of values]

A reference type is a type where the data or value is held in separate memory and only the reference to that memory location is copied when assigned to a constant or variable or when it is passed to some other function. Swift types such as Classes are reference type.When a instance is created, reference to the memory location holding the actual value is copied not the value itself.The newly copied value and the previous value will be the same.

Sample code:

Value and reference type

Leave a Reply