<div dir="ltr"><div>I&#39;ve made an unsuccessful attempt to rewrite the below code in a shorter, more generic way using the improved numeric protocols in Swift 4 (BinaryFloatingPoint, FixedWidthInteger et al). So now I&#39;m wondering if anyone would like to give it a try (or declare that it is not possible).</div><div><br></div><div>The following is the code I wish to rewrite. It is for initializing Double and Float to unit range values (0.0 inclusive to 1.0 exclusive) given a fixed width unsigned integer, ie mapping the full range of the given integer [.min, .max] to the floating point unit range [0, 1).</div><div><br></div><div>It would be nice if the solution also happened to support signed fixed width integers and CGFloat, Float80, but only if it doesn&#39;t make it more complicated.</div><div>The code has to be fast, so any improvement in speed is also appreciated.</div><div><br></div><div><br></div><div>extension Double {</div><div>    init(unitRange v: UInt64) {</div><div>        let shifts: UInt64 = 63 - UInt64(Double.significandBitCount)</div><div>        self = Double(v &gt;&gt; shifts) * (.ulpOfOne/2)</div><div>    }</div><div>    init(unitRange v: UInt32) {</div><div>        self = (Double(v) + 0.5) / (Double(UInt32.max) + 1.0)</div><div>    }</div><div>    init(unitRange v: UInt16) {</div><div>        self = (Double(v) + 0.5) / (Double(UInt16.max) + 1.0)</div><div>    }</div><div>    init(unitRange v: UInt8) {</div><div>        self = (Double(v) + 0.5) / (Double(UInt8.max) + 1.0)</div><div>    }</div><div>}</div><div>extension Float {</div><div>    init(unitRange v: UInt64) {</div><div>        let shifts: UInt64 = 63 - UInt64(Float.significandBitCount)</div><div>        self = Float(v &gt;&gt; shifts) * (.ulpOfOne/2)</div><div>    }</div><div>    init(unitRange v: UInt32) {</div><div>        let shifts: UInt32 = 31 - UInt32(Float.significandBitCount)</div><div>        self = Float(v &gt;&gt; shifts) * (.ulpOfOne/2)</div><div>    }</div><div>    init(unitRange v: UInt16) {</div><div>        let a = Float(v) + 0.5</div><div>        let b = Float(UInt16.max) + 1.0</div><div>        self = a / b</div><div>    }</div><div>    init(unitRange v: UInt8) {</div><div>        let a = Float(v) + 0.5</div><div>        let b = Float(UInt8.max) + 1.0</div><div>        self = a / b</div><div>    }</div><div>}</div></div>