Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

swift methods

I still don't understand swift methods, and what pasan meant by saying "So remember that a method is a function that is associated with a particular type."

2 Answers

Michael Hulet
Michael Hulet
47,913 Points

Methods are exactly like normal functions, except a method is defined within a class, struct, protocol, or enum. To illustrate this:

func someFunction() -> Void{
    // This is a function
}

class SomeObject{
    func someMethod() -> Void{
        // This is a method
    }
}

Thanks so much, that is so helpful. Your explanation is so simple and clear to me. You helped so much!

Brennan White
Brennan White
11,646 Points

In addition to what Michael Hulet said, methods can also be referenced by dot notation on an instance of that struct, class. etc.

class Enemy {
    var life: Int = 1
    let position: Point

    init(x: Int, y: Int) {
        self.position = Point(x: x, y: y)
    }

    func decreaseLife(by factor: Int) {
        life -= factor
    }
}

Since the class Enemy has a method of decreaseLife, an instance of that class can use the method.

let E1 = Enemy(x: 4, y: 5)
E1.decreaseLife(by: 1)

thanks, that was helpful!