Start learning free

LESSON 209 OF 415 · FUNCTIONS & CLASSES

Class Methods in Swift: Adding Behavior

Lesson Read the full explanation

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 Rex
STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · FUNCTIONS & CLASSES

    Class Methods in Swift, explained

    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.bark by itself refers to the method without running it; write rex.bark().
    • Calling on the class. Dog.bark() doesn't work, because bark belongs to objects, which is how it can use name.
    • Forgetting the return. A method declared with -> String must 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.name is changed first, bark prints the new name.

    Key takeaways

    • A method is a func declared 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.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free