Swift: Classes are Reference Types

Classes are Reference Types in Swift:

One of the most important differences between structures and classes is that classes are reference types and structures are value types in Swift.

When a value type is assigned to a variable or constant, or when it is passed to a function, its value is copied. If a company asks for your driver’s licence, you wouldn’t give it to them to keep; instead, you’d make a copy or jot down the information and leave it with them. Your original driver’s licence has not been tampered with. All of Swift’s basic types are value types, including Int, Double, Bool, String, arrays, and dictionaries.

When reference types are assigned to a variable or constant, or passed to a function, they are not copied, unlike value types. A reference to the same existing instance is used instead of a copy.

Here’s an illustration. Assume we have a sunsetLodge instance of the Hotel class:

var sunsetLodge = Hotel() ;
 
sunsetLodge.name = "Sunset Lodge";
sunsetLodge.type = "Resort hotel";
sunsetLodge.rating = 4.1 ;
sunsetLodge.rooms = true ;

Assume that the Hotel‘s owner, Alex, decides to franchise it, and a new one called sunsetLodge2 emerges. If we duplicate the instance and change the value of one of the properties:

var sunsetLodge2 = sunsetLodge ;
sunsetLodge2.rating = 4.6 ;
 
print(sunsetLodge.rating) ;
// Prints: 4.6
print(sunsetLodge.rating) ;
// Prints: 4.6

Notice how, even though sunsetLodge2‘s property changed, sunsetLodge‘s property changed as well. As a result, we must exercise caution when changing the values of a class instance’s property values.

Take a look at the Swift documentation for more information.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: