Why am I not able use round in an extension?

Viewed 110

I'm trying to make this customRound func, but Xcode complaining that can not convert value of type () to Double How could I possibly solve this problem?

extension Double {

    func customRound(zeros: Int) -> Double {
      return round(Double(zeros)*self) / Double(zeros)
    }
    
}

update:

extension Double {

    func customRound(digits: Int) -> Double {
        return Darwin.round(pow(10.0, Double(digits))*self) / pow(10.0, Double(digits))
    }
  
}
2 Answers

Swift thinks you are trying to call the mutating round() function of Double instead of the built-in round() which is part of the Darwin module. You can fix this by explicitly specifying Darwin.round():

extension Double {

    func customRound(zeros: Int) -> Double {
        return Darwin.round(Double(zeros) * self) / Double(zeros)
    }

}

Swift prefers the one defined on Double because it is trying to be helpful. Since you don't have to specify self. when calling a method in an extension, it thinks you meant self.round(...) thus trying to apply the mutating round on self when you wanted the Darwin version.

In addition to using Darwin. to select the desired round function, you can specify any framework that includes Darwin such as UIKit or Foundation.

Double have both .round()and .rounded() with the former being mutating. If you want to return the value, you need to use the latter.

Here's how you can use the non-mutating function Double.rounded()

extension Double {
    func customRound(zeros: Int) -> Double {
        return (Double(zeros) * self).rounded() / Double(zeros)
    }
}

extension Double {
    func customRound(digits: Int) -> Double {
        return (pow(10.0, Double(digits)) * self).rounded() / pow(10.0, Double(digits))
    }
}
Related