Home > Blockchain >  how to extend Double and Int in Swift with the same function
how to extend Double and Int in Swift with the same function

Time:08-10

I want to create an extension for Swift Double, Int, and other numeric types that support the random(in:) function, like so:

extension Double {
    // function to generate multiple random numbers of type
    static func random(in range: ClosedRange<Self>, count: Int) -> [Self] {
        var values = [Self]()
        if count > 0 {
            for _ in 0..<count {
                values.append(Self.random(in: range))
            }
        }
        return values
    }
}

How do I do this without creating a separate extension for each type?

CodePudding user response:

You can't really since there is no common protocol involved here but as far as I understand the types that has the method random(in:) can be grouped into types conforming to two protocols so you need only two implementations

// Double & Float
extension BinaryFloatingPoint {
    static func random(in range: ClosedRange<Self>, count: Int) -> [Self] where Self.RawSignificand: FixedWidthInteger {
       var values = [Self]()
       if count > 0 {
           for _ in 0..<count {
               values.append(Self.random(in: range))
           }
       }
       return values
   }
}

// Int & UInt
extension FixedWidthInteger {
    static func random(in range: ClosedRange<Self>, count: Int) -> [Self] {
       var values = [Self]()
       if count > 0 {
           for _ in 0..<count {
               values.append(Self.random(in: range))
           }
       }
       return values
   }
}
  • Related