Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: definition and syntax of functions vs. closures

Is this a function or a closure?

let triple: Int -> Int = {
    (number: Int) in // What is this?
    let result = 3 * number
    number
    return result
}

triple(1)
like image 394
Rudiger Avatar asked Jun 10 '14 21:06

Rudiger


People also ask

What is difference between closure and function?

Roughly, a closure is a block of code that may capture variable values from its surrounding scope. Roughly, a function is a statically defined block of code that may use variable values from its surrounding scope.

How do you define a closure in Swift?

In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World .

What is the point of closures in Swift?

Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables.

Are closures functions?

A closure is a function that preserves the outer scope in its inner scope.


1 Answers

Swift Closures are defined as follows:

{ (parameters) -> return type in
    statements
}

Thus, your code sample is considered a closure by definition. However, I would rewrite it as follows by moving the return type within the curly braces:

let triple = {
  (number: Int) -> Int in
  let result = 3 * number  
  number
  return result
}

triple(1)

The parameters and return type begin after the opening curly brace and end before the in keyword and the body of the closure begins after the in keyword and ends at the closing curly brace. Next, I would recommend downloading and reading iBook from iTunes which can be found at the following location:

https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11

like image 94
Conrad Taylor Avatar answered Sep 17 '22 19:09

Conrad Taylor