Default Values for Parameters

Swift lets us specify default values for any or all of our parameters. So, We could set ‘end’ to have the default value of 12, which mean that if we don’t specify it, 9 will be used automatically.

func printMultiplicationTables(for number: Int, end: Int = 9) {
    for i in 1...end {
        print("\(number) X \(i) = \(number * i)")
    }
}

printMultiplicationTables(for: 3, end: 7)
printMultiplicationTables(for: 4)

When we call ‘removeAll()’, Swift will automatically remove all the items in an array, and then free up all the memory that was assigned to the array. Sometimes, we might be about to add lots of new items back into the array. So, there’s a second form of this funtion that removes the items while also keeping the previous capacity: ‘.removeAll(keepingCapacity: true)’

var characters = ["Lana", "Pam", "John", "Sterling"]
print(characters.count)

characters.removeAll(keepingCapacity: true)
print(characters.count)



handle Errors in functions

we need to start by dfining the possible errors that might happen. This means making a new enum that builds on Swift’s existing Error type.

enum PasswordError: Error {
    case short, obvious
}


func checkPassword(_ password: String) throws -> String {
    if password.count < 5 {
        throw PasswordError.short
    }
    if password == "12345" {
        throw PasswordError.obvious
    }
    
    if password.count < 8 {
        return "OK"
    }else if password.count < 10 {
        return "Good"
    }else {
        return "Excellent"
    }
    
}

Now we have to run the function and handle any errors that might happen. There are 3 steps to work with real Swift projects.

  1. Starting a block of work that might throw errors, using ‘do’.
  2. Call one or more throwing functions, using ‘try’.
  3. Handling any thrown errors using ‘catch’.
let string = "12345"

do {
    let result = try checkPassword(string)
    print("Password rating: \(result)")
} catch PasswordError.short {
    print("Please Use a longer password")
} catch PasswordError.obvious {
    print("This is too obvious.")
} catch {
    print("There was an error.")
}



Checkpoint 4

Writ a function that accepts an interger from 1 through 10,000, and returns the interger square root of that number. There are some catches.

  1. You can’t use Swift’s built-in ‘sqrt()’ function or similar, you need to find the square root yourself.
  2. if the number is less thatn 1 or greater than 10,000 you should throw an “Out of Bounds” error/
  3. You should only consider interger square roots.
  4. If you can’t find the square root, throw a “No Root” error.
import SwiftUI

enum SquareRootError: Error {
    case lessGreater, notFound
}

func root(_ number: Int) throws -> Int {
    for i in 1...10_000 {
    if number == i * i {
        return i
    }
    }
    
    if number < 1 || number > 10_000 {
            throw SquareRootError.lessGreater
        }else {
            throw SquareRootError.notFound
        }
    }

let sample = 36
do {
    let result = try root(sample)
    print("Root = \(result)")
} catch SquareRootError.lessGreater {
    print("Out of Bounds")
} catch SquareRootError.notFound {
    print("No Root")
} catch {
    print("Something went Wrong!")
}