How do I use mathematical functions like sqrt()
, floor()
, round()
, sin()
, etc?
When doing:
For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.
Instead of floor()
, round()
and the rest of the rounding routines you can use rounded(_:)
:
let x = 6.5
// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"
// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"
// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"
// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"
These are currently available on Float
and Double
and it should be easy enough to convert to a CGFloat
for example.
Instead of sqrt()
there's the squareRoot()
method on the FloatingPoint protocol. Again, both Float
and Double
conform to the FloatingPoint
protocol:
let x = 4.0
let y = x.squareRoot()
For the trigonometric functions, the standard library can't help, so you're best off importing Darwin on the Apple platforms or Glibc on Linux. Fingers-crossed they'll be a neater way in the future.
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
let x = 1.571
print(sin(x))
// Prints "~1.0"