Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 311
Suragch Avatar asked Nov 30 '22 23:11

Suragch


1 Answers

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.

like image 189
Suragch Avatar answered Dec 10 '22 14:12

Suragch