Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical functions in Swift

Tags:

swift

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

like image 530
Giovanni Avatar asked Jun 03 '14 10:06

Giovanni


People also ask

How do you do math in Swift?

Swift is type-safe and only allows mathematical operators to be used on the same types (Int and Int, Long and Long, Float and Float, Double and Double); if you want to perform math on two different types you must either cast one to the type of the other (e.g. 3.0 * Double(4)) or cast them both to some other type (e.g. ...

How do you write pi in Swift?

alt + p is the shortcut (on US-keyboards) that will create the π unicode character.


2 Answers

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

like image 101
Tomáš Linhart Avatar answered Oct 01 '22 17:10

Tomáš Linhart


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

like image 26
bpresles Avatar answered Oct 01 '22 19:10

bpresles