Swift: Structures are Value Types

Structures are Value Types in Swift:

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.

  • We started by creating newCar, a Car instance with the following properties: name: "BMW x5", and speed: 320.
  • We then create a new variable, oldCar, with the same value as newCar.
  • We gave oldCar a speed of 360, but we didn’t do anything with newCar.
  • It prints 360 when we print oldCar.speed.
  • It prints 320 when we print newCar.speed.

We might have assumed that changing oldCar.speed would affect newCar because oldCar was copied from newCar. But, to return to our original point, structs are value types. When we use newCar to create oldCar, 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.

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: