简体   繁体   中英

How can I access the values in this NSDictionary in Swift?

I am trying to access the 'address' object (String) in a dictionary:

Chain.sharedInstance().getAddress("19b7ZG3KVXSmAJDX2WXzXhWejs5WS412EZ"){  dictionary, error in
            NSLog("%@", dictionary)
            let value = dictionary["address"] as? String //returns nil
        }

this is the data I receive:

 results = ( { address = 19b7ZG3KVXSmAJDX2WXzXhWejs5WS412EZ; confirmed = { balance = 0; received = 20000000; sent = 20000000; }; total = { balance = 0; received = 20000000; sent = 20000000; }; } ); } 

How do I access the values in this dictionary when I keep getting nil?

To clarify, the data you are posting is not JSON, but rather looks like JSONP. You aren't showing any code deserializing the the object, so I assume Chain.sharedInstance().getAddress is handling that aspect. If this is an instance of the Bitcoin API, you might look at their documentation. If it is their API, the documentation says the return is

A dictionary with a single "results" key, whose value is a array containing a single Address Object as a dictionary.

If that is the case if would be

if let resultsArray = dictionary["results"] as NSArray {
    if let dict = results[0] as NSDictionary {
        //dict["address"] should have your address
    }
}

Try:

if let dict = dictionary["results"] as NSDictionary
{
     let value = dict["address"] as NSString
}

or:

if let dict = dictionary["results"] as NSArray
{
    if let di = dict[0] as NSDictionary
    {
           let value = di["address"] as NSString
    }

}

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