Define Classes in Swift
Written by Team Kodeco
Classes in Swift are a blueprint for creating objects (also known as instances) of a certain type. They allow you to encapsulate data (stored properties) and behavior (methods) within a single entity.
Here is an example of how to define a class in Swift:
class MyClass {
// properties
var name: String
// initializer
init(name: String) {
self.name = name
}
// method
func printName() {
print(name)
}
}
In this example, You have a class called MyClass
that has one property called name
of type String
. You also have an initializer, which is used to set the initial value of the name
property when an instance of the class is created. Finally, you have a method called printName()
that simply prints the value of the name
property.
To create an instance of the class, we use the following syntax:
let myInstance = MyClass(name: "John")
You can then access the properties and call the methods of the instance:
myInstance.name // John
myInstance.printName() // prints "John"
The rest of this section of the cookbook will go into more detail about how to use classes (and structures) in Swift.