How to Cast Optional<Double> to Optional<int> in Swift

Is there a built in way to convert an optional double to an optional Int in Swift?

I expect that the function should cast Some Double to Some Int and nil -> nil.

Does this exist? I know that I could create a simple extension but I’m hoping that there’s something built-in. When I use Int() I get the expected error of Value of optional type 'Double?' must be unwrapped to a value of type 'Double'

>Solution :

No. There is no built-in other than the Int initializer and you do need to unwrap it before trying to initialize it unless you create an extension and do an optional binding syntax. So the only thing you can do is something like:

extension BinaryFloatingPoint {
    func integer<B: BinaryInteger>() -> B { .init(self) }
    var int: Int { integer() }

let double: Double? = 2.5
let int = double?.int   // optional integer 2

Leave a Reply