-1

I was checking through the Alamofire documentation and found the below code

 Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)

if let json = response.result.value {
    print("JSON: \(json)")
}
}

It seems as if the function is written as

Class.Function().Function{
}

Is this called a nested function? If so how would I create a simple nested function to know the syntax

Pm Abi
  • 225
  • 5
  • 8
  • 1
    That's just method chaining (also mentioned in the Alamofire Readme) – Martin R May 04 '17 at 07:18
  • And for the trailing closure syntax, see for example http://stackoverflow.com/questions/26127427/swift-completion-handler-syntax. – Martin R May 04 '17 at 07:21

2 Answers2

0

It's Method chaining and last one is the syntax of trailing closures.

Closures are self-contained blocks of functionality that can be passed around and used in your code.

    func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
}

// Here's how you call this function without using a trailing closure:

someFunctionThatTakesAClosure(closure: {
    // closure's body goes here
})

// Here's how you call this function with a trailing closure instead:

someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
}

For more information about closures read it

Community
  • 1
  • 1
ankit
  • 3,537
  • 1
  • 16
  • 32
0

this is not a nested function but a chain of functions.

class Alamofire {
    static func request(_ url: String)->Request {
        //... code ...
        return aRequest
    }
}

class Request {
    func responseJson(completion: (response: Response)->()) {
        //code
    }
}

So this is what is happening. The request function of Alamofire is returning a Request object which has the responseJson function that accepts a closure as parameter.

In swift if the closure parameter is the last one, the function call can be synthesized by removing the parameter name and define the closure as a function so to do

Alamofire.request("whatever").responseJson(completion: { (response) in 
    //whatever
})

is exactly the same as doing

Alamofire.request("whatever").responseJson(){ (response) in 
    //whatever
}

This is a trailing closure. You can find more info about it here in the "Trailing Closure" paragraph.

Hope it helps

Giuseppe Lanza
  • 3,519
  • 1
  • 18
  • 40