Learning Swift - Day Four

Done

The Goal

Today is day 4 of learning Swift. I’m going to be focusing on the second book of the Swift documentation “Data and logic” which we will go over basic operators, strings and characters, collection types and control flow.


Basic Operators

Assignment Operator


let b = 10
var a = 5
a = b
// a is now equal to 10
let (x, y) = (1, 2)
// x is equal to 1, and y is equal to 2
if x = y {
    // This isn't valid, because x = y doesn't return a value.
}

Arithmetic Operators

Unary minus operator

let three = 3
let minusThree = -three // minusThree equals -3
let plusThree = -minusThree // plus three equals 3 or "minus minus three"

Unary plus operator

let minusSix = -6
let alsoMinusSix = +minusSix // equals -6

Compound assignment operators

var a = 1
a += 2
// A is now equal to 3.

Comparison Operators

(1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple". Because the first check of 1 is less than 2 the check stops there and doesn't compare the string.

(3, "apple") < (4, "bird") // 3 is not less than 4 so it then moves onto comparing the string and in terms of alphabetical order apple is before bird so apple is true. This then results to the whole tuples being true.

(4, "dog") == (4, "dog") // If the first elements are the same then it returns true but also moves onto the next stage which then compares "dog" and "dog" so if the elements are the same then it still compares the next tuples.

("blue", -1) < ("purple", 1) // OK: Evalutes to true
("blue", false) < ("purple", true) // Error: can't use < to compare boolean.

Ternary conditional operator

if question {
    answer1
} else {
    answer2
}

// OR

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)

Nil-Coalescing operator

a != nil ? a! : b
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

Range Operators

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}

// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
let names = ["Anna", "Alex", "Brian", "Max"]
let count = names.count

for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}

// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brain
// Person 4 is called Max

One-sided ranges

let names = ["Anna", "Alex", "Brian", "Max"]

for name in names[2..] {
    print name
}

// Brian
// Max

for name in names[...2] {
    print(name)
}

// Anna
// Alex
// Brian
let names = ["Anna", "Alex", "Brian", "Max"]

for name in names[..<2] {
    print(name)
}

// Anna
// Alex
let range = ...5

range.contains(7)    // false
range.contains(4)   // true
range.contains(-7)  // true

Logical operators

if (enteredDoorCode && passedRetinaScan) hasDoorKey knowsOverridePassword {
    print("Welcome")
} else {
    print("Access Denied")
}

Strings and characters

var emptyString = ""
var anotherEmptyString = String()
if emptyString.isEmpty {
    print("Nothing to see here")
}

String mutability

var variableString = "Horse"
variableString =+ " and carriage"
// variableString is now "Horse and carriage"

let constantString = "Highlander"
constantString += " and another highlander"
// this reports a compile-time error - a constant string cannot be modified.
for character in "Dog!" {
    print(character)
}
let exclamationMark: Character = "!"
let catCharacters: [Character] = ["C", "A", "T", "!"]
let catString = String(catCharacters)
print(catString)
let string1 = "hello"
let string2 = "world"
var welcome = string1 + string2
var instruction = "look over"
instruction += string2

// OR
let exclamationMark: Character = "!"
welcome.append(exclamationMark)

String interpolation

let hello = "Hello world"
print("\(hello)!")
let hello = "hello"
print("Hello count \(hello.count)")
let greeting = "Hello world"
for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
    // Prints "H e l l o  w o r l d"
}

Inserting and removing

var welcome = "hello"

welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"

welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
var welcome = "Hello world"

welcome.remove(at: welcome.index(before: welcome.endIndex))
// Welcome now equals "hello worl"

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)

// welcome now equals "hello"

Substrings

let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"

// Convert the result to a String for long-term storage
let newString = String(beginning)

Prefix and Suffix equality

let romeoAndJuliet = [
    "Act 1 Scene 1: Verona, A public place",
    "Act 2 Scene 2: Verona, A test",
]

var act1SceneCount = 0

for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1") {
        act1SceneCount += 1
    }
}

for scene in romeoAndJuliet {
    if scene.hasSuffix("test") {
        act1SceneCount += 1
    }
}

Arrays

var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double] and equals [0.0, 0.0, 0.0]
var threeDoubles = Array(repeating: 0.0, count: 3)

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// threeDoubles is of type [Double] and equals [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles
shoppingList += ["Baking Powder"]
for item in shopppingList {
    print(item)
}
for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}

// Item 1: Six eggs
// Item 2: Milk
// so on and so on.

Sets

var letters = Set<Character>()
var favoriteGenres: Set<String> = ["Rock", "Hip Hop"]

Dictonaries

let airportCodes = [String](airport.keys)
let airportNames = [String](airport.values)
let numberOfLegs = ["Spider": 8, "ant": 6]

for (animalName, legCount) in numberOfLegs {
    print(animalName)
    print(legCount)
}

Control flow

let minutes = 60
let minuteInterval = 5

for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    // render the tick mark every 5 minutes (0, 5, 10, 15...)
}

let hours = 12
let hourInterval = 3
for tickMark in stride(for: 3, through: hours, by: hourInterval) {
    // render the tick mark every 3 hours (3, 6, 9, 12)
}

While loops