Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 773
Boon Avatar asked Jun 23 '14 00:06

Boon


1 Answers

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
like image 166
drewag Avatar answered Nov 10 '22 23:11

drewag