2.1 Basic Operators

Types

  • Unary → operates on a single target (- !)
  • Binary → operates on two targets (+ - * /)
  • Ternary → operates on three targets (a ? b : c)

Assignment =

  • does not itself return a value (prevents accidents when == was wanted)
  • a data type cannot be changed once set
// assign a variable
var a = 1
// assign a constant
let b = a
// assign multiple -> c = 4, d = 5.0
let (c, d) = (4, 5.0)
// assign a tuple -> e.0 = 6, e.1 = 7, e.2 = 8
let e = (6, 7, 8)

Arithmetic

  • swift does NOT implicitly convert values when types are mixed
  • values may not overflow by default (use & to force overflow)
+  addition
- subtraction
* multiplication
/ division

Math Functions

// -> 36.55
let absolute = abs(-36.55)
// -> 2
(4.0).squareRoot()
// -> 10
max(5, 10)
// -> -10
min(-5, -10)
// -> 3.14159…
print(Double.pi)

Modulus Operator %

  • operator that tells the remainder left after division
  • only works with Ints and negatives
// modulus % -> -1
let remainderUnits = -9 % 4

Modulus Function

  • works with Ints, Doubles, Floats, and negatives
// modulus function -> 1.8
let remainder = 5.0.truncatingRemainder(dividingBy: 3.2)

Rounding

  • requires a Double to work
let testNumber = -36.55
var roundNumber: Double
// -> -37.0
roundNumber = round(testNumber)
// -> -37.0
roundNumber = floor(testNumber)
// -> -36.0
roundNumber = ceil(testNumber)
// -> -36.0
roundNumber = trunc(testNumber)
// rounding to specific decimal places -> -36.5
let doubleStr = String(format: "%.1f", testNumber)

Shift Operations << or >>

  • shift binary number decimal digits to form a new binary number
  • use only for binary numbers (ie. 00001011)