Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- FUNCTIONS
- */
- func printMessage() {
- let message = "Print this message"
- print(message)
- }
- printMessage() // Calling function
- // ACCEPTING PARAMETERS
- func square(number: Int) {
- print(number * number)
- }
- square(number: 8)
- // RETURNING VALUES
- func squareOfNumber(number: Int) -> Int {
- return number * number
- }
- let result = squareOfNumber(number: 8)
- // EXTERNAL/INTERNAL PARAMETER NAMES
- func sayHello(to name: String) {
- print("Hello, \(name)!")
- }
- sayHello(to: "Taylor")
- func greet(_ person: String) { // Using _ as external parameter
- print("Hello, \(person)!")
- }
- greet("Jim")
- // DEFAULT PARAMETERS
- func studentProgress(name: String, passedTest: Bool = true) {
- if passedTest == true {
- print("\(name) passed the test.")
- } else {
- print("\(name) failed! Boo hoo hoo!")
- }
- }
- studentProgress(name: "Jane") // "Jane passed the test."
- studentProgress(name: "Greg", passedTest: false) // "Greg failed! Boo hoo hoo!"
- // VARIADIC FUNCTIONS
- // Function takes in unlimited number of parameters of same type
- // and converts them into an array
- func squareInput(numbers: Int...) {
- for number in numbers {
- print("\(number) squared is \(number * number)")
- }
- }
- squareInput(numbers: 2, 4, 6) // "2 squared is 4" etc.
- // THROWING FUNCTIONS
- // Create enum based on Swift's Error type.
- enum PasswordError: Error {
- case obvious
- }
- // Use "throws" before return type or body of function
- func checkPassword(_ password: String) throws -> Bool {
- if password == "password" {
- throw PasswordError.obvious
- }
- return true
- }
- // Code that might throw an error is called
- // within DO block
- do {
- try checkPassword("password") // Error thrown, jumps to CATCH block
- print("That password is good!") // Never executed
- } catch {
- print("You can't use that password")
- }
- // INOUT PARAMETERS
- // Place inout before parameter
- func doubleInPlace(number: inout Int) {
- number *= 2 // number = 4
- }
- var myNum = 2 // myNum = 2
- // Remember & before variable being passed
- doubleInPlace(number: &myNum)
- print(myNum) // myNum = 4
Advertisement
Add Comment
Please, Sign In to add comment