5

In Swift PromiseKit library there's Alamofire example using a bit strange syntax:

func login(completionHandler: (NSDictionary?, ErrorProtocol?) -> Void    {
    Alamofire.request(.GET, url, parameters: ["foo": "bar"])
        .validate()
        .responseJSON { response in
            switch response.result {
            case .success(let dict):
                completionHandler(dict, nil)
            case .failure(let error):
                completionHandler(nil, error)
            }
        }
}

response is an Alamofire enum describing two cases with associated values:

public enum Result<Value> {
    case success(Value)
    case failure(Error) 
(...)

What I don't get is what does let mean in each case: line and where does the dict (or error) come from? Is this syntactic sugar for something more verbose but less confusing?

konrad
  • 1,664
  • 2
  • 17
  • 36

1 Answers1

8

In Swift, enums can have associated values (docs). This means, that you can associate an object with cases. The part (let dict) simply means - take the associated value, and put in in a let constant named dict.

Losiowaty
  • 7,911
  • 2
  • 32
  • 47
  • 1
    Ok, so we're basically testing for enum being .success or .failure and the `(let xxx)` part is basically some kind of a shortcut getter for the associated value? – konrad Mar 31 '17 at 12:53
  • 2
    Correct. You can also write it as `case let .success(dict):` – Ashley Mills Mar 31 '17 at 12:54
  • 1
    Swift syntax doesn't cease to surprise me sometimes with shortcuts it allows. :-) – konrad Mar 31 '17 at 12:55
  • Also I'd swear I looked through the docs for enum associated values and it wasn't there but it clearly is. :-) – konrad Mar 31 '17 at 12:59
  • do anyone knows the difference between the two syntax case let .success(value) vs case .success(let value) – Abuzeid May 26 '20 at 16:57
  • The Enumerations document: https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html look for Associated Values section it has a great explaination and example for Bar Codes. – David Nov 10 '22 at 02:48