In Swift, classes are reference types that allow you to create complex data structures and define behavior through methods, properties, and initializers. Classes support inheritance, enabling you to create hierarchies of related types. Let's explore how you can work with classes in Swift.
To define a class in Swift, you use the class
keyword followed by the class name:
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func greet() {
print("Hello, my name is \(name)!")
}
}
To create an instance of a class, you use the class name followed by parentheses. You can then access the properties and methods of the instance:
let person = Person(name: "Alice", age: 30)
print(person.name) // Output: Alice
person.greet() // Output: Hello, my name is Alice!}
You can create a subclass by inheriting from a superclass. Subclasses inherit properties and methods of the superclass and can provide their own implementations:
class Employee: Person {
var role: String
init(name: String, age: Int, role: String) {
self.role = role
super.init(name: name, age: age)
}
override func greet() {
print("Hello, I'm \(name) and I work as a \(role).")
}
}
You can create an instance of a subclass and access properties and methods from both the superclass and the subclass:
let employee = Employee(name: "Bob", age: 35, role: "Developer")
employee.greet() // Output: Hello, I'm Bob and I work as a Developer.}