从 AnyObject 项目列表中获取索引 IOS

Get the index out of AnyObject list of items IOS

parsed 是一个 NsDictionary,我正在通过

从中提取余额

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

这给了我 AnyObject 格式的余额列表

(
    {
    "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;

}
)

我知道

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

=USD 但是,如果对象的数量发生变化,我如何找到该值 [7]?

我想匹配美元

我试过了

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

但这给了我 9223372036854775807

我怎么才能找到 7

9223372036854775807NSNotFound.

您可以使用闭包作为 indexOf

的参数
let  defaultcurr = "USD"
let findUSDIndex = findbalances.indexOf { ([=10=]["currency"] as! String) == defaultcurr }

或者您可以过滤整行

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

indexOfObject 似乎在使用 NSArray。不要那样做。使用 Swift native Array 并将您的集合对象转换为 [[String:AnyObject]] :

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