Welcome to this blog post, where we will embark on a deep dive into Swift classes. In programming languages like Swift, classes form the building blocks of flexible constructs known as Objects.
Utilizing classes to their fullest extent can elevate the functionality and performance of your code.
A class in Swift is a custom type, which allows programmers to create instances (objects) with properties and methods. Think of a class as a blueprint outlining the same characteristics for multiple objects. Each object created from this blueprint is an independent class instance, capable of holding its own set of values for these properties.
To give you a real-life analogy, think of a class called 'Person'. The 'Person' class could have properties like 'name' and 'age', and methods like 'greet' and 'walk'. The 'name' and 'age' are properties, which every class instance of 'Person' will have.
Here's an example of what the 'Person' class might look like:
1class Person { 2 var name: String 3 var age: Int 4 5 init(name: String, initial_Age: Int = 0) { 6 // The initial_Age parameter can have a default value 7 // To simplify instance creation when an age is not specified. 8 self.name = name 9 age = initial_Age 10 } 11 12 func greet() { 13 print("Hello, my name is \(name).") 14 } 15}
In the code snippet above, 'name' and 'age' are stored properties. The 'init' keyword depicts the initial state of the class when creating instances. 'Greet' is a method within the Person class, which when invoked will display a greeting message.
The class keyword is used to define a class in Swift. The 'class' keyword starts with the class definition followed by the class name. The class definition could contain properties, methods, and initializers enclosed in curly braces .
Swift classes have two types of properties: stored properties and computed properties. Stored properties store a value of a certain type, and computed properties calculate a value.
Below is an example showing both stored and computed properties in the class 'Student'.
1class Student { 2 var name: String // Stored property 3 var age: Integer // Stored property 4 var grade: String { // Computed property 5 if age > 17 { 6 return "Senior" 7 } else { 8 return "Junior" 9 } 10 } 11}
Methods(like greet() in the previous example) are functions that provide functionality for the class instances. You can define as many methods as required in your class definition.
Creating a class in Swift is straightforward. We have already seen how to create the ‘Person’ class in the previous examples. You just use the ‘class’ keyword followed by the name of your class. class Person { // class properties and methods go here }
In the Swift standard library, some functionalities are given a default implementation but many times, you will find the need to provide custom implementations.
Repeatedly creating new instances of a class might look cumbersome. To alleviate this, we implement initializers using the ‘init’ keyword. Initializers can use 'default values' for some parameters to make instance creation more flexible.
1class Student { 2 var name: String 3 4 init(name: String) { 5 self.name = name 6 } 7} 8let student = Student(name: "John")
In the above example, we have passed parameters to the initializer to set an initial value for the ‘name’ property.
Class variables (also known as static variables) are variables that have the same value across all class instances. Swift calls these shared variables 'type properties'. In other languages, they are widely known by the term "static class variables".
1class MyClass { 2 static var myVariable: String = "Hello, World!" 3} 4print(MyClass.myVariable) // outputs "Hello, World!"
In the above example, myVariable is a static class variable that belongs to the class, not instances of the class.
Categories in Objective C are a way to add functionality to an existing class without extending it- a concept not inherently available in Swift. Instead, Swift provides extensions that allow adding computed properties and methods to extend existing types.
In Swift classes, it's important to understand how class inheritance works. Class inheritance is the phenomenon where one class (the "child") inherits the properties and methods of another class(the "parent"). Let's look at an example.
1class Person { // Parent class 2 var name: String = "" 3 4 func description() -> String { 5 return "A person named \(name)" 6 } 7} 8 9// The Student class inherits from Person 10class Student: Person { // Child class 11 var grade: String = "" 12 13 override func description() -> String { 14 return "\(super.description()), who is a \(grade) student" 15 } 16}
In the above example, we're using the 'override' keyword to modify the description() method in the Student class. The override keyword is instrumental in Swift class inheritance, enabling the child class to provide unique implementations of the methods inherited from the parent class.
1let student = Student() 2student.name = "John" 3student.grade = "senior" 4print(student.description()) // Outputs "A person named John, who is a senior student"
In the above example, notice how the Student description() method also uses super.description(). The super keyword refers to the parent class, allowing the child class to utilize the parent class's methods or properties.
Swift classes come with further advanced features like Protocols and Extensions. While we won’t delve into more detail in this blog post, they’re worth exploring as you advance in your Swift journey, adding to the versatility of Swift Classes.
Swift classes are 'reference type', which allows for 'more than one reference' to a single class instance. This is a significant distinction from value types, such as structs, which do not share this characteristic.
Being a reference type means that classes in Swift can have multiple references pointing to the same instance, and when changes are made to that instance, they are reflected across all references. This capability is crucial for certain programming patterns and is supported by the underlying reference counting mechanism in Swift.
In this blog post, we've explored Swift Classes in depth, from the creation and usage of class instances to implementing class inheritance and understanding how 'value types' and 'reference types' differentiate Classes from Swift Structures.
We've also used several examples, showcasing class properties (both stored and computed), methods, initializers, and class variables. We hope you've found this dive into Swift classes beneficial and encourage you to continue exploring Swift, a robust and versatile language.
The syntax and concepts discussed here are just the starting point. As with all programming languages, practice, and continuous learning will help you master the usage of classes in Swift, making it a powerful tool in your coding arsenal.
Keep practicing and explore the wide variety of resources available online to continue learning. Swift surely holds a lot more for you. 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.