techguy techguy - 4 months ago 13
iOS Question

Get the index out of AnyObject list of items IOS

parsed is an NsDictionary and I am pulling the balances out of it via

if let findbalances: AnyObject = parsed["balances"]

which gives me a list of balances in AnyObject format

(
{
"available_amount" = 133519;
currency = AUD;
},
{
"available_amount" = 7854;
currency = CAD;
},
{
"available_amount" = 88581;
currency = EUR;
},
{
"available_amount" = 0;
currency = GBP;
},
{
"available_amount" = 63618;
currency = INR;
},
{
"available_amount" = 375;
currency = NZD;
},
{
"available_amount" = 0;
currency = TRY;
},
{

"available_amount" = 2918958;
currency = USD;

}
)


I know that

let whatCurrency = (findbalances[7]["currency"] as! String)


=USD But how do I find that value [7] if the amount of objects changes?

I want to match on USD

I tried

let defaultcurr = "USD"
let findUSD = findbalances.indexOfObject(defaultcurr)


but that gave me 9223372036854775807

How do I just find 7

Answer

9223372036854775807 is NSNotFound.

You can use a closure as argument of indexOf

let  defaultcurr = "USD"
let findUSDIndex = findbalances.indexOf { ($0["currency"] as! String) == defaultcurr }

Or you can filter the entire row

let findUSD = findbalances.filter { ($0["currency"] as! String) == defaultcurr }.first

indexOfObject seems to be using NSArray. Don't do that. Use Swift native Array and cast your collection object to [[String:AnyObject]] :

if let findbalances = parsed["balances"] as? [[String:AnyObject]] { ...