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 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!