Skip to content
Numbers and Math
step 1/5

Reading — step 1 of 5

Learn

~1 min readGetting Started

Standard arithmetic: + - * / %. Integer / truncates: 7 / 3 is 2. For float division, at least one operand must be a Double.

let a = 17
let b = 5
print(a + b)              // 22
print(a / b)              // 3   (integer)
print(Double(a) / Double(b)) // 3.4
print(a % b)              // 2

Swift refuses implicit conversion. To go from Int to Double, wrap with Double(...) — same syntax as a function call.

For advanced math, import Foundation: pow, sqrt, abs, etc. Or use the methods on numeric types directly. Swift has Double.pi, Int.max, Int.min, etc. as type-level constants.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…