Day 10 of HackingWithSwift's 100 days of SwiftUI. Today I learnt about classes in Swift. Classes in Swift are very similar to
Struct since they allow you to create custom data types with properties and methods. Classes in Swift are different from Structs in two major way:
- Classes are reference-based objects while Structs are value-based objects.
- Classes also introduce a new concept called Inheritance. Swift structs do not support inheritance.
Inheritance means you can create new classes(child classes) based on an existing class (parent classes). The child class will inherit properties and methods from its parent class.
class Developer {
var name: String
var occupation: String
init(name: String, occupation: String) {
self.name = name
self.occupation = occupation
}
}
class AndroidDeveloper {
var name: String
var knowsCompose: Bool
init(name: String, knowsCompose: Bool) {
super.init(name: name, occupation: "Android developer")
self.knowsCompose = knowsCompose
}
}
let androidDev = AndroidDeveloper("sanmi", false)
The code above creates two classes: Developer
and Android Developer
. AndroidDeveloper
is a subclass of Developer so it inherits the properties: name and occupation from Developer. When creating the init
block for AndroidDevelopever, you have to initialise the Developer
superclass first.
If you are interested in taking the challenge, you can find it at https://www.hackingwithswift.com/100/swiftui
See you tomorrow ;)
Top comments (0)