Mathematical functions in Swift

Solution 1:

As other noted you have several options. If you want only mathematical functions. You can import only Darwin.

import Darwin

If you want mathematical functions and other standard classes and functions. You can import Foundation.

import Foundation

If you want everything and also classes for user interface, it depends if your playground is for OS X or iOS.

For OS X, you need import Cocoa.

import Cocoa

For iOS, you need import UIKit.

import UIKit

You can easily discover your playground platform by opening File Inspector (⌥⌘1).

Playground Settings - Platform

Solution 2:

To be perfectly precise, Darwin is enough. No need to import the whole Cocoa framework.

import Darwin

Of course, if you need elements from Cocoa or Foundation or other higher level frameworks, you can import them instead

Solution 3:

For people using swift [2.2] on Linux i.e. Ubuntu, the import is different!

The correct way to do this is to use Glibc. This is because on OS X and iOS, the basic Unix-like API's are in Darwin but in linux, these are located in Glibc. Importing Foundation won't help you here because it doesn't make the distinction by itself. To do this, you have to explicitly import it yourself:

#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif

You can follow the development of the Foundation framework here to learn more


EDIT: December 26th, 2018

As pointed out by @Cœur, starting from swift 3.0 some math functions are now part of the types themselves. For example, Double now has a squareRoot function. Similarly, ceil, floor, round, can all be achieved with Double.rounded(FloatingPointRoundingRule) -> Double.

Furthermore, I just downloaded and installed the latest stable version of swift on Ubuntu 18.04, and it looks like Foundation framework is all you need to import to have access to the math functions now. I tried finding documentation for this, but nothing came up.

➜ swift          
Welcome to Swift version 4.2.1 (swift-4.2.1-RELEASE). Type :help for assistance.
  1> sqrt(9)
error: repl.swift:1:1: error: use of unresolved identifier 'sqrt'
sqrt(9)
^~~~


  1> import Foundation
  2> sqrt(9)
$R0: Double = 3
  3> floor(9.3)
$R1: Double = 9
  4> ceil(9.3) 
$R2: Double = 10

Solution 4:

You can use them right inline:

var square = 9.4
var floored = floor(square)
var root = sqrt(floored)

println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")