Please note that with the current version of Swift, the solution below is already implemented in the standard library, and all mathematical functions are correctly overloaded for Double , Float and CGFloat .
Ceil is an arithmetic operation, and just like any other arithmetic operation, there must be an overloaded version for Double and Float .
var f1: Float = 1.0 var f2: Float = 2.0 var d1: Double = 1.0 var d2: Double = 2.0 var f = f1 + f2 var d = d1 + d2
This works because + overloaded and works for both types.
Unfortunately, pulling the math functions from the C library, which does not support function overloading, we leave two functions instead of one - Ceil and ceilf .
I think the best solution is Ceil overload for Float types:
func ceil(f: CFloat) -> CFloat { return ceilf(f) }
Lets us do:
var f: Float = 0.5 var d: Double = 0.5 var f: Float = ceil(f) var d: Double = ceil(d)
Once we have the same operations as for Float and Double , even handling CGFloat will be much easier.
To reply to a comment:
Depending on the architecture of the target processor, CGFloat may be defined as Float or Double . This means that we must use Ceil or ceilf depending on the target architecture.
var cgFloat: CGFloat = 1.5
However, we would have to use the ugly #if .
Another option is to use smart tricks.
var cgFloat: CGFloat = 1.5 var rounded: CGFloat = CGFloat(ceil(Double(cgFloat))
(discarding Double first and then outputting the result to CGFloat )
However, when we work with numbers, we want mathematical functions to be transparent.
var cgFloat1: CGFloat = 1.5 var cgFloat2: CGFloat = 2.5 // this works on both 32 and 64bit architectures! var sum: CGFloat = cgFloat1 + cgFloat 2
If we reload Ceil for Float as shown above, we can do
var cgFloat: CGFloat = 1.5 // this works on both 32 and 64bit architectures! var rounded: CGFloat = ceil(cgFloat)