Education
Software Development Executive - II
Last updated onNov 13, 2024
Last updated onMay 15, 2024
When we talk about Swift Objects, we're stepping into the realm of Object-Oriented Programming (OOP) - a programming model that makes use of objects encapsulating state and behavior. Swift, as an object-oriented programming language, has objects at its heart, making them integral to any Swift-related development.
An object in Swift is an instance of a class and is a central concept in Swift. Objects are instances of classes that contain properties and methods that can be used within the same class or by multiple objects to communicate and perform tasks.
As you delve into the world of Swift, you'll be introduced to various concepts, including the class keyword, default values, and swift classes, that form the foundation of objects in Swift. This blog provides a comprehensive insight into these concepts to help you create multiple objects efficiently.
1class Student { 2 var name = "John Doe" 3 var age = 21 4}
In the code snippet above, Student is a swift class and name and age are its properties. To create an instance of a class or an object, we use the class keyword Student(), like this:
1let studentObject = Student()
Understandably, mastering objects—creating and manipulating them—is key to harnessing the power of the Swift language. Let's dive systematically into these concepts, starting with the building blocks of Swift Objects—class in Swift.
Swift Classes are at the core of creating Swift objects. They are flexible constructs that form the blueprint from which objects are created. They are defined using the class keyword, followed by the class name:
1class ClassName { 2 // class properties and methods go here 3}
Take a class named Bike as an example:
1class Bike { 2 var name: String 3 var color: String 4 init(name: String, color: String) { 5 self.name = name 6 self.color = color 7 } 8}
Here, Bike is a class in Swift, and var name, and var color are its mutable class properties. The class constructor (init()) provides initial values to the class properties when creating a new instance.
A swift class is composed of properties and methods. Properties store values, which can be of any type—value type or reference type. They can have a default initial value, as in var name = "Bike". This is a string var name, and the default value is hardcoded as "Bike".
Methods, on the other hand, provide functionality. They are used to modify properties and methods of the same class. Here is an example of a method in the Person class:
1class Person { 2 var name: String 3 init(name: String) { 4 self.name = name 5 } 6 func greet() { 7 print("Hello, \(self.name)!") 8 } 9}
In the class Person, greet() is a class method that prints a greeting.
Swift also supports computed properties that don't hold a specific value but provide a getter and an optional setter to calculate a value.
1class Bike { 2 var speed: Double 3 // computed property 4 var speedInMilesPerHour: Double { 5 get { 6 return speed * 0.62 7 } 8 set { 9 speed = newValue / 0.62 10 } 11 } 12} 13 14let bike = Bike(speed: 32) 15println(bike.speedInMilesPerHour) 16// prints "19.84"
In the Bike class, speedInMilesPerHour is a computed property. It's a way to customize the process of setting and retrieving values.
Now that you've had an introduction to classes in Swift let's put these concepts to use and delve into the life of Swift Classes - the class instance.
The class instance is a realization of a class. When you create an instance, Swift assigns default values to the class properties, enabling the class instance to take on its initial form.
This process of creating a new instance of a class is simple in Swift, using the initializer syntax:
1class ClassName { 2 init(parameters) { 3 // assign values to properties 4 } 5}
You can create an instance of the class named Bike we defined above as follows:
1let myBike = Bike(name: "Mountain Bike", color: "Red")
Here, myBike is an instance of the Bike class.
Swift allows each property to have default values, providing a default initial value. This initial value is the value that a class property is assigned at the time an instance is instantiated:
1class Student { 2 var name: String = "John Doe" 3 var age: Int = 21 4}
In the class Student above, every new instance created from this class will have a default initial name of "John Doe" and age of 21.
Backing our knowledge with hands-on understanding, let's move forward to learn about working with objects in Swift.
Swift, as a statically typed language, requires at runtime the type of each class instance. One can print the type of any swift object using the type(of:) function. This function is handy when you want to know about the class of an object.
1class Person { 2 var name: String 3 init(name: String) { 4 self.name = name 5 } 6} 7 8let person = Person(name: "John Doe") 9print(type(of: person)) // Outputs: Person
In this example, type(of: person) prints Person, the class of the object person.
Understanding and creating objects in Swift is just the start. A significant portion of object-oriented programming in Swift involves manipulating class instances and communicating between multiple objects.
To create a swift object, you first declare a class, define its properties and methods, and then instantiate it.
1class ClassName { 2 var name: String 3 init(name: String) { 4 self.name = name 5 } 6 func methodName() { 7 // method implementation goes here 8 } 9} 10 11let objectName = ClassName(name: "Object Name")
In the above example, you create a swift object named objectName of class ClassName.
Once you have an existing instance of a class, Swift allows you to alter it using the dot syntax.
1let john = Person(name: "John Doe") 2john.name = "Johnny" 3print(john.name) // Outputs: "Johnny"
Here, we modified the name property of the john object from "John Doe" to "Johnny". Swift allows you to do much more with objects, such as calling class methods, interacting with computed properties, and more. But, let's not get ahead of ourselves and move onto some more advanced topics related to Swift Objects.
Objects in Swift are more than standalone instances of classes. They can have relationships like class inheritance, reference multiple objects, and much more.
Inheritance is a core concept of object-oriented programming, where a class (the child class) can inherit the properties and methods of an existing class (the parent class).
Consider this parent class, Vehicle:
1class Vehicle { 2 var color: String 3 init(color: String) { 4 self.color = color 5 } 6}
We can create a child class, Car, that inherits from Vehicle:
1class Car: Vehicle { 2 var brand: String 3 init(color: String, brand: String) { 4 self.brand = brand 5 super.init(color: color) 6 } 7}
In this example, Car is a class that inherits from Vehicle. super.init(color: color) is used to call the initializer of the parent class.
In Swift, class instances are reference types. This means that when you assign a class instance to a variable or constant, or pass it as a function parameter, you are passing a reference to the same data, not a copy of the data. This is referred to as reference counting.
1let carOne = Car(color: "Black", brand: "Porsche") 2let carTwo = carOne 3carTwo.color = "Red" 4print(carOne.color) // Outputs: "Red"
In the code above, carOne and carTwo refer to the same instance of the Car class. A change in the color of carTwo reflects in carOne as well. This highlights one of the most compelling aspects of working with Swift Objects.
Now, let's take a step back, reflect on our learnings, and understand why Swift Objects are the cornerstone of Swift programming.
Harnessing the full potential of Swift involves a comprehensive understanding of Swift Objects and how to use them efficiently. The core concepts we've covered in this blog post are the fundamentals you'll use every day in Swift programming.
Think of a class as a blueprint for objects, where you define properties and methods. You then bring those blueprints to life by creating class instances or objects. You can assign default values to properties, use the dot syntax to access and modify those properties, and use class methods to define behaviors.
Additionally, Swift provides computed properties to customize the process of setting and retrieving values. Also, by using the concept of class inheritance, you can create a hierarchy of classes to share code in a structured manner and build on existing code.
Finally, understanding that Swift objects are reference types is pivotal. It makes it clear that any changes made through one reference will impact all the other references pointing to the same instance.
With these basic principles, your understanding of Swift Objects will deepen as you continuously code and iterate on your Swift projects.
In conclusion, understanding Swift objects is fundamental to mastering Swift, an object-oriented programming language. From defining and instantiating a class, and assigning default values for properties to understanding inheritance and reference types—every aspect contributes to the full understanding of Swift objects.
The knowledge applied in real-world programming scenarios helps write clean, efficient, and more readable Swift code. Keep exploring Swift and embrace the power and flexibility it offers. Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.