GregLeck

Closures - Part I

Sep 28th, 2019
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.66 KB | None | 0 0
  1. /*
  2.  CLOSURES - PART ONE
  3.  */
  4. // Closures are methods that are assigned to variables that can be called using that variable and even passed to other functions.
  5. // They are functions without a name and are written differently than named functions
  6.  
  7. // BASIC CLOSURE
  8. let driving1 = {
  9.     print("I'm driving in my car")
  10. }
  11. driving1()   // Calling closure like regular function
  12.  
  13. // ACCEPTING PARAMETERS
  14. // Parameters goes inside curly braces followed by "in"
  15. // and placed before body of closure.
  16. let driving2 = { (place: String) in
  17.     print("I'm driving to \(place) in my car")
  18. }
  19. // When calling closure, parameter label isn't used:
  20. driving2("Montreal")    // "I'm  driving to Montreal in my car"
  21.  
  22. // RETURNING VALUES
  23. // Return type placed after parameters but before "in"
  24. let driving3 = { (place: String) -> String in
  25.     return "I'm driving to \(place) in my car"
  26. }
  27. let message = driving3("London")
  28. print(message)
  29.  
  30. // CLOSURES AS PARAMETERS
  31. // Return to basic closure that accepts no values
  32. // and returns no value and would be expressed as:
  33. // () -> Void
  34. let driving4 = {
  35.     print("I'm driving in my car")
  36. }
  37. // Create function that accepts closure as parameter:
  38. func travel(action: () -> Void) {
  39.     print("I'm getting ready to go.")
  40.     action()
  41.     print("I have arrived.")
  42. }
  43. // Call function with closure as parameter:
  44. travel(action: driving4)
  45.  
  46. // TRAILING CLOSURE SYNTAX
  47. // If the last parameter in a function is a closure,
  48. // we can pass it directly after the function call.
  49. travel() {
  50.     print("I'm driving in my car")
  51. }
  52. // If the function accepts no other parameters,
  53. // the () can be elminated.
  54. travel {
  55.     print("I'm driving in my car.")
  56. }
Advertisement
Add Comment
Please, Sign In to add comment