【问题标题】:swift Dictionary error快速字典错误
【发布时间】:2014-07-15 21:09:44
【问题描述】:

我有这个功能:

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()
}

我收到了这个错误:
'(String, AnyObject)' 不能转换为 'Int'
在这行

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

我不知道为什么

内容是数组
-> 玩家是 KeyValue
-> 播放器是字典
-> player["id"] 是 AnyObject

那么为什么他认为 player["id"] 是 '(String, AnyObject)'??

谢谢

更新

更改为修复该错误:

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

但现在我在运行时得到了这个:

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

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    循环中的playerDictionary&lt;String, AnyObject&gt; 的一个实例。因此,存储在该字典中的值是 AnyObject 的实例。

    在这一行:

    let id : Int = player["id"]
    

    您正在尝试进行从 AnyObjectInt 的隐式转换,这是不可能的。正确的处理方法是:

    1. 解包从字典中提取的值(如果键不存在,则可以是nil
    2. 显式转换为Int

    所以该行应该固定如下:

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

    也可以简写为:

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

    类似的规则适用于scorename

    附录 - 根据您的最后一个错误,可能是由于字典中没有键。尝试使用这样的选项:

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

    您有 3 个可选变量,如果右侧的相应表达式的计算结果为 nil,则它们会得到 nil。如果可行,请使用调试器检查字典中没有哪个键

    【讨论】:

    • 它修复了该错误.. 但现在我在同一行的运行时出错:线程 5:EXC_BREAKPOINT (code=EXC_ARM_BREAKPOINT,subcode=0xdefe)
    • 请检查我的答案
    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多