99

How do I use mathematical functions like sqrt(), floor(), round(), sin(), etc?


When doing:

_ = floor(2.0)
_ = sqrt(2.0)

I get:

error: use of unresolved identifier 'floor'
error: use of unresolved identifier 'sqrt'

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
Giovanni
  • 1,313
  • 1
  • 10
  • 14
  • If you get the `Ambiguous reference to x` check this answer out: http://stackoverflow.com/a/34357943/1359306 – Patrick Jan 30 '16 at 23:25

6 Answers6

101

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

Tomáš Linhart
  • 13,509
  • 5
  • 51
  • 54
78

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

bpresles
  • 781
  • 4
  • 3
  • And with Swift 3+, you don't need Darwin (or Glibc) for `sqrt`, `floor` and `round` because you may natively use respectively `0.5.squareRoot()`, `Int(0.5)` and `0.5.round()`. – Cœur Oct 10 '18 at 10:04
17

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
smac89
  • 39,374
  • 15
  • 132
  • 179
  • And with Swift 3+, you don't need Darwin (or Glibc) for `sqrt`, `floor` and `round` because you may natively use respectively `0.5.squareRoot()`, `Int(0.5)` and `0.5.round()`. – Cœur Oct 10 '18 at 10:08
  • @Cœur, I've been out of touch with swift for a while. Perhaps you can offer this insight in the form of an answer. Thanks – smac89 Oct 10 '18 at 22:21
  • For `pow` I needed to include `Glibc` for Linux, thanks! – A1rPun Sep 18 '19 at 19:34
10

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)")
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
  • 1
    I get the following error: use of unresolved identifier 'sqrt'. – Giovanni Jun 03 '14 at 10:23
  • I think it's expecting me to declare a function called sqrt, but obviously it's not what I want. Thanks – Giovanni Jun 03 '14 at 10:23
  • You need to import UIKit, or Cocoa, or Foundation. – Ben Gottlieb Jun 03 '14 at 10:50
  • is there a function where I can give it an array of Ints and then Swift would return me a function of power of 2 (or 1, or 3, or whatever) that best matches it? like I give it: `[1,2,3]` it would return `y = x` or I would give it [1,4,9] it would return `y = x^2` or something just close in that manner of `f(x)` – mfaani Feb 13 '17 at 19:39
  • It's working for me, but my playground imports UIKit by default. And it works too, importing Foundation or Darwin instead UIKit. – Timbergus Jun 07 '17 at 13:53
8

To use the math-functions you have to import Cocoa

You can see the other defined mathematical functions in the following way. Make a Cmd-Click on the function name sqrt and you enter the file with all other global math functions and constanst.

A small snippet of the file

...
func pow(_: CDouble, _: CDouble) -> CDouble

func sqrtf(_: CFloat) -> CFloat
func sqrt(_: CDouble) -> CDouble

func erff(_: CFloat) -> CFloat
...
var M_LN10: CDouble { get } /* loge(10)       */
var M_PI: CDouble { get } /* pi             */
var M_PI_2: CDouble { get } /* pi/2           */
var M_SQRT2: CDouble { get } /* sqrt(2)        */
...
DanEEStar
  • 6,140
  • 6
  • 37
  • 52
4

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"
Tricky
  • 7,025
  • 5
  • 33
  • 43