Evgeniy Kleban
Evgeniy Kleban

Reputation: 6975

Cannot use mutating member on immutable value Swift

I want write an extension to Double so it func will give Int values.

extension Double {
  func toPercentage() -> Int {
    var mutableSelf = self
    var twoDigits = Double(round(1000*mutableSelf)/1000)
    return Int(twoDigits) * 100
  }
}

On line var twoDigits = Double(round(1000*mutableSelf)/1000) compiler throw red - Cannot use mutating member on immutable value: 'self' is immutable

But i did reassign self to mutableSelf variable. Double is a struct, and it's not reference type, why error appears?

Upvotes: 1

Views: 992

Answers (2)

Martin R
Martin R

Reputation: 540105

Since you are in an extension of Double, the compiler infers round() to be the mutating func round() method of Double, even though the call does not match its signature. This behavior has been reported as a bug:

You can refer to the global C library function with

extension Double {
    func toPercentage() -> Int {
        let twoDigits = Darwin.round(1000*self)/1000
        return Int(twoDigits * 100)
    }
}

or better, use the Double.rounded() method:

extension Double {
    func toPercentage() -> Int {
        let twoDigits = (1000*self).rounded()/1000
        return Int(twoDigits * 100)
    }
}

or simply

extension Double {
    func toPercentage() -> Int {
        return Int((100 * self).rounded())
    }
}

Upvotes: 6

Jaydeep Vora
Jaydeep Vora

Reputation: 6223

extension Double {
    func toPercentage() -> Int {
        let twoDigits = Double((1000 * self / 1000).rounded())
        return Int(twoDigits) * 100
    }
}

Upvotes: 1

Related Questions