Day 5 – Functions

[cc_swift width=”100%” height=”100%”] // functions func printHelp() { let message = “”” Hi and welcome to this fabulous thing. This is a help message I’ll print throughout my long program so it’s best I put it in a function. “”” print(message) } printHelp() /// accepting parameters func square (number: Int) { print(number * number) } square(number: 8) /// returning values and parameter labels func returnSquare (of number: Int) -> Int { //of: external, number: internal return number * number } returnSquare(of: 8) /// omitting parameter labels (kind of like the print function) func greet(_ person: String) { print(“Hello, \(person)”) } greet(“Maria”) /// default parameters func greeting(_ person: String, nicely: Bool = true) { if nicely { print(“Hello, \(person)”) } else { print(“Ugh, \(person) again?”) } } greeting(“Micaela”) greeting(“Micaela”, nicely: false) /// variadic functions //// that is, they can accept any number of parameters of a certain type //// we do that by adding ‘…’ after the type, swift converts them to an array func variadicSquare(_ numbers: Int…) { for number in numbers { print(“The square of \(number) is \(number * number)”) } } variadicSquare(23, 34, 45, 56, 57) /// throwing functions //// we can have functions throw errors, if we so wish. this may be because of //// a variety of reasons. let’s say we are making a function which checks //// passwords, and throws an error when the passwoord is too obvious. We start //// by creating this ‘obvious’ type out of an Error-type enum enum PasswordError: Error { case obvious } //// we then throw the error in the function before return func checkPassword(_ password: String) throws -> Bool { if password == “1234” { throw PasswordError.obvious } return true } //// calling throwing functions ///// do, try, and catch do { try checkPassword(“1234”) print(“Good password.”) } catch { print(“Password too bad.”) } ///// catch is run in case of an error, try runs when there’s no error. wrap the ///// whole thing in a do. /// inout parameters //// normally when we pass parameters, the function can’t change them outside //// of the function func doubleInPlace(number: inout Int) { number *= 2 } var myNumber = 10 doubleInPlace(number: &myNumber) [/cc_swift]

Leave a Reply

Your email address will not be published. Required fields are marked *