Search code examples
swiftswift-extensions

Calling mutating func on an Int extension


Created an extension in a command line app. When I tried calling the calc method, it won't work. Calling desc works.

What did I miss?

protocol Calculatable {
    var desc:String { get }
    mutating func calc()
}

class MyClass : Calculatable {
    var desc:String = "MyClass"
    func calc()  {
        desc += " is great"
    }
}

extension Int: Calculatable {
    var desc:String { return "hi" }
    mutating func calc() {
        self += 10
    }
}

7.desc  // works
7.calc() // Compiler error: could not find member calc

Solution

  • That is because 7 is a constant. You can do it if you first store it in a variable:

    var number = 10
    number.calc()
    

    Note: The error you are getting isn't a very good error. Swift definitely has some work to do on that side of things. The real error is that you are trying to call a mutating method on an immutable instance

    What you can do is make it a regular method and return a new value instead of trying to mutate self:

    extension Int: Calculatable {
        var desc: String { return "hi" }
        func calc() -> Int {
            return self + 10
        }
    }
    
    7.calc() // 17