Data types in Swift can be either value types or reference types. Different data types are stored and accessed in different ways as a result of this. Structures are value types in Swift, which means that each time an instance is created or copied, it has a unique set of values. In a separate lesson, we’ll go over different types of references.
Consider the following scenario:
var newCar = Car(name: "BMW x5", speed: 320) ; var oldCar = newCar ; oldCar.speed = 360 ; print(newCar.speed) ; // Prints: 320 print(oldCar.speed) ; // Prints: 360
From the preceding example, there are a few nuanced points to discuss.
Carinstance with the following properties:
name: "BMW x5", and
oldCar, with the same value as
360, but we didn’t do anything with
360when we print
320when we print
We might have assumed that changing
oldCar.speed would affect
oldCar was copied from
newCar. But, to return to our original point, structs are value types. When we use
newCar to create
oldCar only stores the values of
newCar. The lesson here is that any changes we make to an instance of a structure, such as
oldCar, will not affect other instances’ properties.
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.