简体   繁体   中英

Values from nested array in Swift 3

I am using Swift 3.

I am getting the following response from a server and i need to parse and get values such as, Account No, Account Type, Address etc.

parsedData: (
        {
        key = "<null>";
        offset = 1;
        partition = 0;
        topic = test;
        value =         {
            "Account No" = 675;
            "Account Type" = Saving;
            Address = location;
            User ID = 601;
            User Name = Stella;
        };
    }
)

I have been trying to get value first, and then planning to get each value,

var temp: NSArray = parsedData["value"] as! NSArray

but this is giving error as cannot convert value of type String to expected argument type Int.'

How to retrieve values from the above mentioned array?

parsedData is an array which contains Dictionary at first index.

let dicData = parsedData[0] as! Dictionary

let valueDictionary = dicData["value"] as! Dictionary  //dicData  also contains dictionary for key `value`


let accountNumber = valueDictionary ["Account No"] //**Account number**

//////SECOND APPROACH IF YOU HAVE DICTIONARY IN RESPONSE

var valueDictionary : NSDictionary = parsedData["value"] as? NSDictionary 
    let accountNumber = valueDictionary ["Account No"] //**Account number**

您将字典解析为数组

var temp: NSDictionary = parsedData["value"] as? NSDictionary 

Try this

let dicData = parsedData[0] as! Dictionary
var temp: NSDictionary = dicData["value"] as? NSDictionary
let accountNumber = temp.object(forKey: "Account No")
let accountType = temp.object(forKey: "Account Type")
let address = temp.object(forKey: "Address")
let userID = temp.object(forKey: "User ID")
let userName = temp.object(forKey: "User Name")

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