Welcome to our in-depth guide on Value Types and Reference Types in Swift! In this tutorial, we'll explore these essential concepts, diving deep into their implications, and providing practical examples to help you understand them clearly.
In Swift, all data types can be categorized into two main groups: Value Types and Reference Types. Let's dive into each one.
Value types, also known as structures and enumerations, hold their own memory space. When you assign a value type variable to another variable, a copy of the original is created. This is why they are called value types.
struct Point {
var x: Int
var y: Int
}
var origin = Point(x: 0, y: 0)
var pointA = origin
// Modifying 'pointA' doesn't affect 'origin' because they're separate instances.
pointA.x = 10
print(origin.x) // 0
print(pointA.x) // 10š Note: Swift's built-in types like Int, Float, Bool, and Character are also considered value types.
Reference types, also known as classes, hold only a reference (memory address) to the actual data. When you assign a reference type variable to another variable, both variables now reference the same memory location. This means changes made to one variable will be reflected in the other.
class Rectangle {
var width: Double
var height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
}
var square = Rectangle(width: 4.0, height: 4.0)
var rectangle = square
// Modifying 'rectangle' affects 'square' because they reference the same instance.
rectangle.width = 5.0
print(square.width) // 5.0
print(rectangle.width) // 5.0š Note: Array, Dictionary, and Optional are Swift's built-in reference types.
When deciding between value types and reference types, consider the following factors:
Which of the following statements is correct about Swift's built-in types?
Happy coding! š