Classes are fundamental building blocks in Swift, enabling object-oriented programming. They provide a powerful way to create custom data types with properties and methods.
In Swift, you define a class using the class
keyword. Here's a simple example:
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func introduce() {
print("Hello, I'm \(name) and I'm \(age) years old.")
}
}
This class defines a Person
with properties for name and age, an initializer, and a method to introduce the person.
To create an instance of a class, you use the class name followed by parentheses:
let john = Person(name: "John", age: 30)
john.introduce() // Outputs: Hello, I'm John and I'm 30 years old.
One of the key features of classes in Swift is inheritance. A class can inherit properties and methods from another class:
class Student: Person {
var grade: String
init(name: String, age: Int, grade: String) {
self.grade = grade
super.init(name: name, age: age)
}
override func introduce() {
super.introduce()
print("I'm in grade \(grade).")
}
}
In this example, Student
inherits from Person
and adds a grade
property. It also overrides the introduce()
method.
override
keyword when overriding inherited methods.While classes and Structures share many similarities, they have key differences:
Class | Struct |
---|---|
Reference type | Value type |
Supports inheritance | No inheritance |
Can have deinitializers | No deinitializers |
When working with classes in Swift, consider these best practices:
Classes in Swift provide a robust foundation for building complex, object-oriented applications. By understanding their features and best practices, you can create efficient and maintainable code.