简体   繁体   中英

Swift access dictionary value

I have a Rails api that I am using to develop my iOS application with. I am currently using alamofire to perform HTTP requests and am running into an issue when trying to access dictionary keys.

Type of the response from Alamofire is __NSDictionaryI .

AF.request("\(url)/wishlist", method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
            switch response.result {
            case .failure(let err):
                print(err)
            case .success(let res):
                print(type(of: res))
                print(res["message"])
            }
        }

I am coming from Ruby where we access hash keys like hash["key"] but am running into issues when trying to do that here. The response from this request prints

{
    message = "Care was created";
    status = ok;
}

I was hoping I could do res["message"] to access that value to pass to a toast message. However, I am unable to compile due to the following error

Value of type 'Any' has no subscripts

Can anybody explain what is happening here and why I am unable to capture this value?

Your first step should be to learn Swift and forget about any assumptions into which Ruby may have led you. Ruby and Swift are opposites. Ruby has no typing ("duck typing") and any variable can adopt any value. Swift has strict typing and a variable must declare its type at the outset and can never change that type.

You can supply a type by casting the response result to a definite type. For instance, you might cast it to [String:Any] . That's a dictionary (similar to Ruby hash) and can be subscripted.

It would be better, however, to decode the response content into a struct with a message property and status property, each of those being properly typed, rather than settling for the typeless responseJSON . You shouldn't say Any unless you really have to, and you rarely have to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM