You Can Do This In Swift

This isn’t a hidden feature or anything – it’s just how optional binding works – but I guess what I didn’t get before was that this (responseObject’s type is AnyObject):

func fetchUserInfoWithCompletion(completion: (ErrorType?, [String: AnyObject])->()) {
    executeGETRequestForURL(userInfoURL) { error, responseObject in

        guard let dictionary = responseObject as [String: AnyObject], fooInfo = dictionary["foo"] {
            completion(error)
        }

        completion(nil, fooInfo)
    }
}

Could become:

func fetchUserInfoWithCompletion(completion: (ErrorType?, [String: AnyObject])->()) {
    executeGETRequestForURL(userInfoURL) { error, responseObject in
        completion(error, responseObject?["foo"] as? [String: AnyObject])
    }
}

So much better. So much code to delete now. Put this under the category of “things I can’t believe I didn’t get until now.”

Collin Donnell @collin