0

I want to add a round method with the specific rounding digits to my RealmOptional class. If you want to add the method to your CGFloat class, you can write the following (I borrow it from this answer):

public extension CGFloat {
  func roundToDecimals(decimals: Int = 2) -> CGFloat {
        let multiplier = CGFloat(10^decimals)
        return round(multiplier * self) / multiplier
    }
}

Is it possible to add this functionality to the RealmOptional class, where only type defined as Float must be added the method to.

I can't get how it shall be implemented, but the following spit out the error:

Type 'T' constrained to non-protocol type 'Float'

import RealmSwift
extension RealmOptional where T: Float {
    func roundToDecimals(decimals: Int = 2) -> CGFloat {
        let multiplier = CGFloat(10^decimals)
        return round(multiplier * self.value!) / multiplier
    }
}
Community
  • 1
  • 1
Blaszard
  • 30,954
  • 51
  • 153
  • 233

1 Answers1

1

As a workaround, you can define a protocol, let the wrapped type implement that and then use the protocol as the generic constraint and delegate to the method implemented on the value, as seen below.

import QuartzCore

protocol Roundable {
    func roundToDecimals(decimals: Int) -> CGFloat
}

extension Float : Roundable {
    func roundToDecimals(decimals: Int = 2) -> CGFloat {
        let multiplier = pow(10.0, Float(decimals))
        return round(multiplier * CGFloat(self)) / multiplier
    }
}

extension RealmOptional where T: Roundable {
    func roundToDecimals(decimals: Int = 2) -> CGFloat {
        return self.value!.roundToDecimals(decimals)
    }
}

But I'd recommend instead to use maybeFloat.value!.roundToDecimals(2) to make the unsafe force-unwrapping clear in the calling code and not hiding it away in the implementation.

Blaszard
  • 30,954
  • 51
  • 153
  • 233
marius
  • 7,766
  • 18
  • 30