P. 51: What does CGFloat(truncating:) do?

Code:

return UIColor(red: CGFloat(truncating: red) / 255.0,
               green: CGFloat(truncating: green) / 255.0,
               blue: CGFloat(truncating: blue) / 255.0,
               alpha: 1)

What does truncating do?

1 Like

It converts NSNumber to CGFloat.

I can read the docs. What I want to know is what’s the difference between CGFloat(exactly:) and CGFloat(truncating:) besides the first one being fallible:

    let x = NSNumber(value: 3.123456789123456789)
    let r1 = CGFloat(exactly: x)
    let r2 = CGFloat(truncating: x)
    
    if let r1 = r1 {
        print("r1 = \(r1)")
    }
    
    print("r2 = \(r2)")

output:

r3 = 3.12345678912346
r2 = 3.12345678912346

This topic was automatically closed after 166 days. New replies are no longer allowed.