2.2 Comparison Operators

x == y    Equal to
x != y Not equal to
x > y Greater than
x >= y Greater than or equal to
x < y Less than
x <= y Less than or equal to
x === y Two objects are equal
x !== y Two objects are not equal
  • comparison operators return true/false and can be stored as a Bool
  • must Type Cast to a common type (ie. all Ints, Doubles…)
let x = 100, y = 200

// -> true
let b1 = x < y // -> false
let b2 = x == y

// -> true
(1, "zebra") < (2, "apple") // -> true
(3, "apple") < (3, "bird") // -> true
(4, "dog") >= (4, "dog")
  • tuples evaluate the first item unless more info is needed 

Ternary Conditional Operator

Question ? <true value> : <false value>

  • returns one of two values based on if the question is true or false
let pop = 5000
let pop2 = 2000

// -> 2000
let minimum = pop < pop2 ? pop : pop2 // -> small town
let message = pop < 9999 ? "small town" : "\(pop) is big!" // -> true
pop >= 5000 ? "We're good" : "Oops, not quite"

Nil-Coalescing Operator ??

  • use when a variable might have a value or be nil
  • if no value, then use a default value
var personalSite: String?
let defaultSite = "http://www.lyfebug.com"

// without ?? operator
let website: String
if personalSite != nil {
   website = personalSite!
} else {
   website = defaultSite
}

// with ?? operator
let website2 = personalSite ?? defaultSite

Identity Operators ===

  • used to determine if two vars/cons refer to the same instance of a class
  • === → identical
  • !== → not identical to
class C {
var varX = 1
}

let classOne = C()
let classTwo = C()
let classThree = classOne

// -> might be equal…
if classOne === classTwo {
print("Identical")
} else {
print("Maybe equal, but not identical")
}

// -> Yes
if classOne === classThree {
print("Yes, they refer to the same object.")
}