2

My data contains user data of various values (which I can parse out) then balances for each user in a number of currencies.

I can parse out the user data. For example:

if let add2 = parsed["address"] as? String {
    println("Alert: \(add2)")
}

I can get the lists of balances:

if let findbalances = parsed["balances"]{    
           println("find the balances: \(findbalances)")

and I can get the individual values:

var balance11:Double = findbalances[0]["available_amount"] as! Double/100

var curr11:String = findbalances[0]["currency"] as! String

The array is AnyObject. If I try:

for currency in findbalances {

I get

Type AnyObject does not conform to Sequence

So then I tried to downcast it to String:

if let findbalances = parsed["balances"] as? String {
for currency in findbalances {

and my output is blank.

Yet I know the values are there.

I am stumped; how do you loop through an AnyObject Array in Swift?

0

1 Answer 1

3

I think you're close. In your code "for currency in findbalances {", you should know that currency is a dictionary, not the currency. Were you looking for something like this?

for balance in findbalances as! [[String: AnyObject]] {
    let currency = balance["currency"] as! String
    //do something with currency
}
Sign up to request clarification or add additional context in comments.

7 Comments

as should be as! or as?
I think that's only the case if findbalances is an optional right? If it's a ! already, the "as" should work? I'm assuming it's not an optional since he's pulling data directly like he was... I guess in that case, he wouldn't need the "as [[String: AnyObject]]" at all.
since Swift 1.2, as has to be either as! or as?.
Ok, fixed it. @techguy, note if the compiler complains you may be able to remove the "as" portion from the findbalances if it was originally defined properly.
@Jaconbson not quite – casts that aren’t guaranteed at compile time to succeed (such as AnyObject to something else) have to be as[?!]. But some casts are guaranteed at compile time to work every time (such as the other way – something else to AnyObject) and they can still be as
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.