Is it possible to write mutating function in swift class?

921 Views Asked by At

I am able to write mutating functions in structure but not in class.

struct Stack {
    public private(set) var items = [Int]() // Empty items array

    mutating func push(_ item: Int) {
        items.append(item)
    }

    mutating func pop() -> Int? {
        if !items.isEmpty {
           return items.removeLast()
        }
        return nil
    }
}
3

There are 3 best solutions below

0
sDev On BEST ANSWER

In swift, classes are reference type whereas structures and enumerations are value types. The properties of value types cannot be modified within its instance methods by default. In order to modify the properties of a value type, you have to use the mutating keyword in the instance method. With this keyword, your method can then have the ability to mutate the values of the properties and write it back to the original structure when the method implementation ends.

0
matt On

If you change the struct to a class, just delete the keyword mutating wherever it appears.

0
Zaphod On

That's because classes are reference types, and structures are value types.

struct TestValue {
    var a : Int = 42

    mutating func change() { a = 1975 }
}

let val = TestValue()
val.a = 1710 // Forbidden because `val` is a `let` of a value type, so you can't mutate it
val.change() // Also forbidden for the same reason

class TestRef {
    var a : Int = 42

    func change() { a = 1975 }
}

let ref = TestRef()
ref.a = 1710 // Allowed because `ref` is a reference type, even if it's a `let`
ref.change() // Also allowed for the same reason

So on classes, you don't need to specify if a function is mutating or not, because, even when defined with let variables, you can modify the instance...

That's why the mutating keyword has no meaning on classes.