Welcome back to CodeYourCraft! Today, we're going to dive into one of the fundamental building blocks of Swift programming ā Classes. By the end of this lesson, you'll be well-versed in creating and utilizing classes to build robust and maintainable code.
In Swift, a class is a blueprint for creating and managing objects (also known as instances) in your application. Think of a class as a template for creating objects that have properties and behaviors.
Let's start by creating a simple class named Person. Open your Swift File (.swift) and type the following code:
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}š” Pro Tip: The init keyword is used to create an initializer, which is a special method that sets initial values for the properties of a class.
In our example above, we have two properties: name and age. These properties define characteristics of the objects (instances) we'll create using the Person class.
Now that we have our Person class, let's create an instance of it:
let johnDoe = Person(name: "John Doe", age: 30)With this line of code, we've created an instance of the Person class named johnDoe and initialized it with the provided name and age.
To access the properties of an instance, simply use the dot notation (.) as follows:
print("Name: \(johnDoe.name)")
print("Age: \(johnDoe.age)")Classes can also contain methods, which are functions associated with a class. Let's add a sayHello method to our Person class:
class Person {
// ...
func sayHello() {
print("Hello! My name is \(name)")
}
}Now, call the sayHello method for johnDoe:
johnDoe.sayHello()This will print "Hello! My name is John Doe" in the console.
Swift allows for class inheritance, where one class inherits the properties and methods of another class. This enables us to create a hierarchy of classes and reuse code.
For example, let's create a Student subclass that inherits from Person.
class Student: Person {
var enrollmentNumber: Int
init(name: String, age: Int, enrollmentNumber: Int) {
self.enrollmentNumber = enrollmentNumber
super.init(name: name, age: age)
}
}š” Pro Tip: Use the super keyword to call the initializer of the superclass.
Now, let's create a student instance and call its methods:
let student = Student(name: "Student A", age: 18, enrollmentNumber: 123456)
student.sayHello()
print("Enrollment Number: \(student.enrollmentNumber)")Classes are essential for building complex applications in Swift. They help manage data, encapsulate behavior, and create maintainable code. By understanding classes, you'll be well-prepared to build your own Swift projects.
What is a class in Swift?
How do you create an instance of a class in Swift?
Keep learning and coding with CodeYourCraft! In the next lesson, we'll explore more advanced concepts related to classes, including inheritance, protocols, and extensions.
Happy coding! š¤š©āš»