Value And Reference Types In Swift

Ahmed Ramadan
2 min readFeb 9, 2024

--

In Swift variables and constants can hold either value types or reference types, which are totally different in terms of memory management and assignment lets make short difference between them

Value type

Value types in Swift include fundamental data types like integers, tuples, floats, doubles, booleans, structs and enums etc ….

each instance keeps a unique copy of its data. A type that creates a new instance (copy) when assigned to a variable or constant, or when passed to a function. As when you assign a value type to a variable or pass it as a parameter to a function, a new copy of the value is created without affecting on the main variable. When we look in the memory we see that we take the main variable and copy it in another place so when any changes happens it only happens on the copy data only.

Note :

Value types Stored on Stack Memory.

Example

Use a value type

  • In comparing data ==
  • When You want copies to have independent state.

Reference type

Reference types in Swift include fundamental data types like Functions ,classes and closures etc…

When you assign a reference type to a variable or pass it as a parameter to a function, you’re not creating a new copy of the instance. you’re creating a reference to the same instance and any change happen to the reference data it affect the both. When we look in the memory we see that we take reference from a variable its just creating a reference to the same instance in memory any modifications happen to the instance through one reference will be reflected in all other references to that instance.

Note :

Reference types Stored on Heap Memory.

Example

Use a reference type

  • Comparing instance identity with === checks if two objects are exactly identical
  • When You want to make shared some thing when any changes happen it changes in the whole app

This is simply the difference

--

--