Another one of the biggest main distinctions between structures and classes is that:
- Structures are value types
- Classes are reference types
A value type is a type whose value is copied when it’s assigned to a variable or constant, or when it’s passed to a function. For example, if a company asks for your driver’s license, you wouldn’t give them your driver’s license to keep - you’d make a copy of it or jot down the info and leave that with them. Your original driver’s license remains untouched. All the basic types in Swift,
String, arrays, and dictionaries, are value types.
Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used.
Here’s an example. Suppose we have an instance of a
Restaurant class called
var krustyKrab = Restaurant() krustyKrab.name = "The Krusty Krab" krustyKrab.type = ["Seafood", "Burgers"] krustyKrab.rating = 2.4 krustyKrab.delivery = true
Suppose the owner Eugene decides to franchise the restaurant and there’s a new one called
krustyKrab2. If we copy the instance and assign one of the properties a new value:
var krustyKrab2 = krustyKrab krustyKrab2.rating = 4.1 print(krustyKrab.rating) // Prints: 4.1 print(krustyKrab2.rating) // Prints: 4.1
Notice how that even though we are changing
krustyKrab‘s property also changed. That’s why we have to be careful when changing the property values of a class instance.
For more reading, take a look at the Swift documentation.
Let’s return to our
Orders example. Suppose there’s a technical difficulty and one of the orders,
order1 did not go through and the customer has been waiting!
Create a new variable called
order8 and copy
order1 into it.
order8.total a value of
0.0 because we shouldn’t ask the customer to pay again.
Print out both