OneBite.Dev - Coding blog in a bite size

Declare An Object In Swift

Code snippet for how to Declare An Object In Swift with sample and detail explanation

Swift is a programming language that is easy to learn, powerful to use, and offers a plethora of features for developers. When dealing with objects in Swift, we follow an object-oriented approach to retain data and functionality.

Code Snippet: Declaring an Object in Swift

class Car {
    var color = "Red"
    var speed = 100
}
  
let myCar = Car()

Code Explanation for Declaring an Object in Swift

In the code snippet above, we are declaring a ‘Car’ object and its properties. Here’s a step by step breakdown:

  1. First, we declare a class named Car. This class encapsulate data and functionalities for car objects.

  2. Within the Car class, we then declare two variables: ‘color’ and ‘speed’. These represent properties of a Car object. The ‘color’ property is of type String, and the ‘speed’ property is of type Int.

  3. After defining the class, we declare a new object of the Car class by assigning it to a constant variable named ‘myCar’. The ‘let’ keyword is used to declare a constant.

  4. let myCar = Car() create a new instance of the Car and assigns it to ‘myCar’. It’s important to remember that in Swift, objects are reference types, which means the constant ‘myCar’ is a reference to the new Car object.

Finally, should you wish to access or manipulate the Car properties, you can do so via the ‘myCar’ reference. For example, myCar.color = "Blue" would change the color of the car from Red to Blue.

swift