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<br>
var a = 1<br>
// assign a constant<br>
let b = a                            <br>
// assign multiple -> c = 4, d = 5.0<br>
let (c, d) = (4, 5.0)<br>
// assign a tuple -> e.0 = 6, e.1 = 7, e.2 = 8<br>
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<br>
-  subtraction<br>
*  multiplication<br>
/  division

Math Functions

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

Modulus Operator %

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

Modulus Function

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

Rounding

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

Shift Operations << or >>

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