Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Generics in Swift Generics and Protocols Associated Types

Peter Correa
Peter Correa
17,155 Points

Why do we have the need to use *mutating func* and not just *func*?

Why do we have the need to use mutating func and not just func?

1 Answer

Tassia Castro
seal-mask
.a{fill-rule:evenodd;}techdegree
Tassia Castro
iOS Development Techdegree Student 9,170 Points

Hey Peter,

You use mutating func when the func can change (or mutate) one or more properties of a Struct.

Check out this example.

struct Rectangle {
    var width = 1
    var height = 1

    func area() -> Int {
        return width * height
    }
}

As you can see the func here is not mutating and the reason is because the method only returns the width times the height without changing it.

struct Rectangle {
    var width = 1
    var height = 1

    mutating func scaleBy(value: Int) {
        width *= value
        height *= value
    }
}

However if I need to create a method that actually change those variables I need to define it as mutating. scaleBy does exactly that, it receives a value and set width and height with them.

Peter Correa
Peter Correa
17,155 Points

Great explanation! Thank you!