Swift equivalent of ceilf for CGFloat
Asked Answered
C

1

6

I was trying to do something like this

var myCGFloat: CGFloat = 3.001
ceilf(myCGFloat)

but ceilf only takes Float values. While searching around there were lots of different answers about doing this conversion or that depending on whether it is 32 or 64 bit architecture.

It turns out the solution is fairly easy but it took me too long to find it. So I am writing this Q&A pair as a shortcut for others.

Caridadcarie answered 15/12, 2015 at 10:4 Comment(2)
Related question here: https://mcmap.net/q/1631027/-cgfloat_type-amp-swift.Moorish
@MartinR, Your answer there was what I was looking for yesterday, but my search keywords didn't turn it up. Thanks for posting the link.Caridadcarie
C
23

The Swift way to do this now is to use rounded(.up) (or round(.up) if you want to change the variable in place). Behind the scenes it is using ceil, which can take a CGFloat as a parameter and is architecture independent.

let myCGFloat: CGFloat = 3.001
let y = myCGFloat.rounded(.up) // 4.0

This is equivalent to

var myCGFloat: CGFloat = 3.001
let y = ceil(myCGFloat) // 4.0

Any use of ceilf is no longer necessary.

See also my fuller answer on CGFloat with various rounding rules.

Caridadcarie answered 15/12, 2015 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.