What a method is
Fields hold an object's data; methods are its behavior. A method is a function declared inside a class, and it can read and change that object's properties directly. When you call rex.bark(), the method sees rex's own data.
Defining and calling a method
class Dog {
var name: String
init(_ name: String) {
self.name = name
}
func bark() {
print("Woof! I am \(name)")
}
}
A method uses the same func syntax as any function. Leaving out the return type means it returns nothing (Void). Call it on an object with the dot operator:
let rex = Dog("Rex")
let luna = Dog("Luna")
rex.bark()
luna.bark()
The output is Woof! I am Rex and then Woof! I am Luna. The same code in bark ran twice, but each time name belonged to the object the method was called on.
Properties inside methods
Inside a method, name is shorthand for self.name. You only need to write self. when a local name hides the property, for example a parameter that is also called name.
Methods can change properties and return values, too:
class Dog {
var name: String
var age = 0
init(_ name: String) { self.name = name }
func birthday() { age += 1 }
func describe() -> String { return "\(name), \(age)" }
}
let rex = Dog("Rex")
rex.birthday()
print(rex.describe()) // Rex, 1
The call rex.birthday() changes the object's age even though rex is a let constant, because Dog is a class. (A struct would need its method marked mutating and a var variable.) Parameters work as in any function, including argument labels: a method func rename(to newName: String) is called as rex.rename(to: "Max").
The exercise
The starter Dog already has a name and an initializer that takes an unlabeled argument, Dog("Rex"). Add a bark method beneath it. The first step declares it empty, and the second prints "Woof! I am " followed by the name, using string interpolation:
class Dog {
var name: String
init(_ name: String) {
self.name = name
}
func bark() {
print("Woof! I am \(name)")
}
}
class Solution {
func mainFunction() {
let rex = Dog("Rex")
rex.bark()
}
}
The program prints Woof! I am Rex. Interpolation, \(name), puts the current value of name into the string, so no + is needed.
Methods calling methods
A method can call another method of the same class by name, without a dot, because the call is made on self implicitly. That lets you build larger behaviors from small ones:
class Dog {
var name: String
init(_ name: String) { self.name = name }
func bark() { print("Woof! I am \(name)") }
func greet() {
bark()
bark()
}
}
Calling greet() on a dog prints its bark line twice. Keeping each method short and focused makes the class easier to read and to change later.
Methods and plain functions
A method differs from a free-standing function in one respect: it is attached to an object and has access to that object's properties. A free function only sees what you pass to it. If a piece of code needs the dog's name, making it a method means you never have to pass the name in; the method already has it.
That attachment is also why the same method name can exist in several classes. A Cat class could have its own func speak() with different behavior, and the compiler picks the right one from the type of the object in front of the dot.
Common mistakes
- Calling without parentheses.
rex.barkby itself refers to the method without running it; writerex.bark(). - Calling on the class.
Dog.bark()doesn't work, becausebarkbelongs to objects, which is how it can usename. - Forgetting the return. A method declared with
-> Stringmust return a value on every path. - Expecting a snapshot. A method reads the property when it runs, not when the object was created. If
rex.nameis changed first,barkprints the new name.
Key takeaways
- A method is a
funcdeclared inside a class. - Call it on an object with
object.method(). - Methods read and write the object's properties directly;
self.is optional unless a name is hidden. - A method without
->returns nothing.
