Like most programming languages, Swift comes with the ability to create classes. Here are some examples of basic class syntax in Swift 3.
To define the class, use the class
keyword followed by the name of your class. Classes their entire definition within a pair of curly braces.
class Colour {
}
You can then create an instance of the class.
var colour = Colour()
Put simply, a property is a constant or variable that is stored as part of an instance of a particular class.
Variables are defined using the var
keyword, and constants are defined using let
.
class Person {
var name: String = "John Doe"
let isHuman: Bool = true
}
We can access these properties by using the dot notation after creating an instance of the class.
var person = Person()
print(person.name) // Prints: John Doe
You also have the ability to change the property value.
var person = Person()
person.name = "Jane Doe"
print(person.name) // Prints: Jane Doe
Note that this does not mean the property value in the class will be permanently changed. This is just for the particular class instance.
var person = Person()
person.name = "Jane Doe"
print(person.name) // Prints: Jane Doe
var person2 = new Person()
print(person2.name) // Prints: John Doe
Methods are functions that belong to instances, such as a particular class. They are defined using the func
keyword. The code within the method should be within a pair of curly braces and the method should be contained within the class declaration.
class Person {
func sayHello() {
print("Hello!")
}
}
Similar to properties, methods can be accessed using the dot notation.
class Person {
func sayHello() {
print("Hello!")
}
}
var person = Person()
person.sayHello() // Prints: Hello!
Classes can also implement an initialisation process. This usually involves setting an initial value for each stored property on that instance. It is written using the init
keyword.
class Square {
var height: Int
var width: Int
init() {
// perform some initialisation here
height = 20
width = 20
}
}
var square = Square()
print("We have a square that has a height of \(square.height) and a width of \(square.width)")
// Prints: We have a square that has a height of 20 and a width of 20
Note: This article is based on Swift version 3.