Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- CLOSURES - PART ONE
- */
- // Closures are methods that are assigned to variables that can be called using that variable and even passed to other functions.
- // They are functions without a name and are written differently than named functions
- // BASIC CLOSURE
- let driving1 = {
- print("I'm driving in my car")
- }
- driving1() // Calling closure like regular function
- // ACCEPTING PARAMETERS
- // Parameters goes inside curly braces followed by "in"
- // and placed before body of closure.
- let driving2 = { (place: String) in
- print("I'm driving to \(place) in my car")
- }
- // When calling closure, parameter label isn't used:
- driving2("Montreal") // "I'm driving to Montreal in my car"
- // RETURNING VALUES
- // Return type placed after parameters but before "in"
- let driving3 = { (place: String) -> String in
- return "I'm driving to \(place) in my car"
- }
- let message = driving3("London")
- print(message)
- // CLOSURES AS PARAMETERS
- // Return to basic closure that accepts no values
- // and returns no value and would be expressed as:
- // () -> Void
- let driving4 = {
- print("I'm driving in my car")
- }
- // Create function that accepts closure as parameter:
- func travel(action: () -> Void) {
- print("I'm getting ready to go.")
- action()
- print("I have arrived.")
- }
- // Call function with closure as parameter:
- travel(action: driving4)
- // TRAILING CLOSURE SYNTAX
- // If the last parameter in a function is a closure,
- // we can pass it directly after the function call.
- travel() {
- print("I'm driving in my car")
- }
- // If the function accepts no other parameters,
- // the () can be elminated.
- travel {
- print("I'm driving in my car.")
- }
Advertisement
Add Comment
Please, Sign In to add comment