Search code examples
jsonswiftenumsclosuresalamofire

How does "let JSON" work in Alamofire/Swift


From here I see that the proper Alamofire 2/Swift 2 syntax when dealing with a JSON response is:

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { request, response, result in
    switch result {
    case .Success(let JSON):
        print("Success with JSON: \(JSON)")

    case .Failure(let data, let error):
        print("Request failed with error: \(error)")

        if let data = data {
            print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
        }
    }
}

How and where is the let JSON defined? (From a Swift point of view.)

I see in a request extension that ResponseSerializer returns .Success(JSON) but why is the handler not defined like a usual function:

case .Success(JSON: AnyObject?) {
    print("Success with JSON: \(JSON)")
}

or better yet:

case .Success(JSON: NSDictionary?) {
    print("Success with NSDictionary: \(JSON)")
}

Solution

  • result is enum with cases .Success, .Failure. Enum cases in Swift can hold some value (by the way, that's how Optionals in Swift work, they are enums with two cases Some: which wraps a value and None). By calling case .Success(let JSON): in switch you assign this value to JSON constant and you can use it in case block. Type of this constant is automatically inferred.

    For more information about it, check paragraph "Associated Values" in Swift Language Guide