Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading