1
votes

I have this func:

typealias KeyValue = Dictionary<String,AnyObject>
func response( response: NSHTTPURLResponse!, data: AnyObject!, error: NSError! ) {

    var resData = data as NSDictionary

    if( resData["status"] as Int == 1 ){

        var content = resData["content"] as Array<KeyValue>

        for player in content {

            let id      : Int       = player["id"]
            let score   : Int       = player["score"]
            let name    : String    = player["name"]

            players[ id ]!.setName( name )
            players[ id ]!.setScore( score )
        }

    } else {
        println( resData["error"] )
    }

    self.playersList.reloadData()
}

and i'm getting this error:
'(String, AnyObject)' is not convertible to 'Int'
on this lines

let id      : Int       = player["id"]
let score   : Int       = player["score"]
let name    : String    = player["name"]

I can't figure out why

content is Array
-> player is KeyValue
-> player is Dictionary
-> player["id"] is AnyObject

so why he think that player["id"] is '(String, AnyObject)'??

Thanks

UPDATE

Change to this fix that error:

let id      = player["id"]!     as Int
let score   = player["score"]!  as Int
let name    = player["name"]!   as String

But now i'm getting this in run-time:

Thread 5: EXC_BREAKPOINT (code=EXC_ARM_BREAKPOINT,subcode=0xdefe) 
1

1 Answers

1
votes

player in your loop is an instance of Dictionary<String, AnyObject>. So values stored in that dictionary are instances of AnyObject.

In this line:

let id : Int = player["id"]

you are trying to make an implicit cast from AnyObject to Int, which is not possible. The correct way to handle that is to:

  1. Unwrap the value extracted from the dictionary (it can be nil if the key doesn't exist)
  2. explicitly cast to Int

So that line should be fixed as follows:

let id : Int = player["id"]! as Int

which can also be shortened as:

let id = player["id"]! as Int

Similar rules apply for score and name

Addendum - as per your last error, probably it is caused by the fact that a key is not in the dictionary. Try using optionals like this:

let id = (player["id"] as AnyObject?) as? Int
let score = (player["score"] as AnyObject?) as? Int
let name = (player["name"] as AnyObject?) as? String

You have 3 optional variables, which get nil if the corresponding expression at the right side evaluates to nil. If that works, use the debugger to check which key is not in the dictionary