GregLeck

Functions

Sep 27th, 2019
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.17 KB | None | 0 0
  1. /*
  2.  FUNCTIONS
  3.  */
  4. func printMessage() {
  5.     let message = "Print this message"
  6.     print(message)
  7. }
  8. printMessage() // Calling function
  9.  
  10. // ACCEPTING PARAMETERS
  11. func square(number: Int) {
  12.     print(number * number)
  13. }
  14. square(number: 8)
  15.  
  16. // RETURNING VALUES
  17. func squareOfNumber(number: Int) -> Int {
  18.     return number * number
  19. }
  20. let result = squareOfNumber(number: 8)
  21.  
  22. // EXTERNAL/INTERNAL PARAMETER NAMES
  23. func sayHello(to name: String) {
  24.     print("Hello, \(name)!")
  25. }
  26. sayHello(to: "Taylor")
  27.  
  28. func greet(_ person: String) {  // Using _ as external parameter
  29.     print("Hello, \(person)!")
  30. }
  31. greet("Jim")
  32.  
  33. // DEFAULT PARAMETERS
  34. func studentProgress(name: String, passedTest: Bool = true) {
  35.     if passedTest == true {
  36.         print("\(name) passed the test.")
  37.     } else {
  38.         print("\(name) failed! Boo hoo hoo!")
  39.     }
  40. }
  41. studentProgress(name: "Jane")   // "Jane passed the test."
  42. studentProgress(name: "Greg", passedTest: false) // "Greg failed! Boo hoo hoo!"
  43.  
  44. // VARIADIC FUNCTIONS
  45. // Function takes in unlimited number of parameters of same type
  46. // and converts them into an array
  47. func squareInput(numbers: Int...) {
  48.     for number in numbers {
  49.         print("\(number) squared is \(number * number)")
  50.     }
  51. }
  52. squareInput(numbers: 2, 4, 6) // "2 squared is 4" etc.
  53.  
  54. // THROWING FUNCTIONS
  55. // Create enum based on Swift's Error type.
  56. enum PasswordError: Error {
  57.     case obvious
  58. }
  59.  
  60. // Use "throws" before return type or body of function
  61. func checkPassword(_ password: String) throws -> Bool {
  62.     if password == "password" {
  63.         throw PasswordError.obvious
  64.     }
  65.     return true
  66. }
  67.  
  68. // Code that might throw an error is called
  69. // within DO block
  70. do {
  71.     try checkPassword("password")   // Error thrown, jumps to CATCH block
  72.     print("That password is good!") // Never executed
  73. } catch {
  74.     print("You can't use that password")
  75. }
  76.  
  77. // INOUT PARAMETERS
  78. // Place inout before parameter
  79. func doubleInPlace(number: inout Int) {
  80.     number *= 2                 // number = 4
  81. }
  82. var myNum = 2                   // myNum = 2
  83. // Remember & before variable being passed
  84. doubleInPlace(number: &myNum)
  85. print(myNum)                    // myNum = 4
Advertisement
Add Comment
Please, Sign In to add comment