TL ; DR:
A method is a function that lives inside a class. Each object can call its methods, and the methods can read and write the object's fields.
Define a method like a regular function, but inside the class body:
class Dog { var name: String = "" func bark() { print("Woof! I am \(name)") } }
Call it on an object with the dot operator:
dog.bark()
Full lesson:
So far you've added data to a class with fields and constructors. The other half of OOP is behavior — actions an object can perform. That's what methods are for.
Defining a method
class Dog {
var name: String = ""
func bark() {
print("Woof! I am \(name)")
}
}
The method can directly read the name field. When you call rex.bark(), the method sees rex's name.
Your task
Add a bark() method to Dog that prints "Woof! I am " followed by the dog's name.
Woof! I am RexFree plan: 30 tutor messages. Premium is unlimited.