Pass by Reference Explained in Swift
Swift classes are reference types. When you pass a class as an argument to a function, the function receives a reference to the memory location where the object is stored.
This means that when you change the object inside the function, you also change the original instance.
Here’s how it works!
class Subscriber {
var name: String
init(_ subscriberName: String) {
self.name = subscriberName
}
}
func changeSubscriberName(_ newSubscriberName: Subscriber) {
newSubscriberName.name = "Emily"
}
var subscriber = Subscriber("Chico")
print(subscriber.name) // Chico
changeSubscriberName(subscriber)
print(subscriber.name) // Emily
In this example, the Subscriber class has a name property of type string and an initializer method that initializes the property.
The changeSubscriberName function accepts one parameter named newSubscriberName and it’s of type Subscriber.
Note: newSubscriberName now holds a reference to the same instance of the Subscriber object that is passed to the function.
Inside the function, the name property of newSubscriberName is assigned the value “Emily.”
领英推荐
Next, the Subscriber class is instantiated with the value “Chico” and assigned to the variable named subscriber.
The name property of subscriber is printed and the result is “Chico.” As expected.
Then the changeSubscriberName( ) function is called and subscriber is passed to it as an argument.
The second time that the name property of subscriber is called, the output is “Emily.”
Here’s why…
This happened because newSubscriberName and subscriber are references to the same instance of the Subscriber class.
In other words, newSubscriberName and subscriber are pointing to the same memory location where the Subscriber class is stored. For this reason, modifying newSubscriberName.name directly modifies subscriber.name because they point to the same instance.
newSubscriberName acts like an alias for the subscriber object.
Because Subscriber is a class, and class instances are passed by reference, when you update one reference, you update the original.