Swift Classes
A class is a blueprint for objects that are shared by reference. Each object made from a class holds its own properties and methods.
Making an object with init
The init method fills the name and age properties when the dog is made. The prints read both properties back.
class Dog {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let dog = Dog(name: "Pip", age: 3)
print(dog.name)
print(dog.age)A method on the object
The greet method builds a line of text from the name property. The call prints that line.
class Dog {
var name: String
init(name: String) {
self.name = name
}
func greet() -> String {
return "Woof from \(name)"
}
}
let dog = Dog(name: "Pip")
print(dog.greet())Changing a property
The age property takes a new value through the dog name. The print shows the new age of 4.
class Dog {
var age: Int
init(age: Int) {
self.age = age
}
}
let dog = Dog(age: 3)
dog.age = 4
print(dog.age)Two names, one object
The second name holds the same box as the first name. Changing the value through the second name makes the first name print 9 too.
class Box {
var value: Int
init(value: Int) {
self.value = value
}
}
let first = Box(value: 5)
let second = first
second.value = 9
print(first.value)
print(second.value)Example
class Wallet {
var coins: Int
init(coins: Int) {
self.coins = coins
}
func add(amount: Int) {
coins += amount
}
}
let wallet = Wallet(coins: 10)
let shared = wallet
shared.add(amount: 5)
print(wallet.coins)Key points
- A class is a blueprint for objects that are shared by reference.
- An init method sets the starting values of the properties when an object is made.
- Inside init, self names the object being made.
- A property is read or changed through the object name, a dot, and the property name.
- A method is a function placed inside a class.
- Two names can hold the same object, so a change through one name shows through the other.
In this example, the Wallet class holds a coins property, and init starts it at 10. The shared name holds the same wallet object as the wallet name. The add call through shared raises the coins to 15, and the print through wallet shows that same 15.
Note
A struct copies on assignment, while a class shares. Swift code usually reaches for a struct first for plain data.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
Two constants hold the same Box object, and the value property is changed to 9 through one of them. What does the other constant read for value?