Search code examples
swiftcgfloatceil

Swift equivalent of ceilf for CGFloat


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.


Solution

  • 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.