【问题标题】:Swift AnyObject as Dictionary get element that doesn't exist is not nilSwift AnyObject 作为 Dictionary 获取不存在的元素不是 nil
【发布时间】:2016-01-20 14:55:30
【问题描述】:

我在 Swift 中遇到了演员问题

这里是代码:

 init(response: NSHTTPURLResponse, representation: AnyObject)
{
    super.init(entity:NSEntityDescription.entityForName("File", inManagedObjectContext: NSManagedObjectContext.currentContext())!, insertIntoManagedObjectContext:NSManagedObjectContext.currentContext());

    var result : [String:AnyObject] = representation as! [String : AnyObject];
    if representation["result"] != nil {
        print("result = \(representation["result"])")
        result = representation["result"] as! [String : AnyObject]
    }
}

在某些情况下,我希望表示 [“result”] 等于 nil,在这种情况下,当我打印表示 [“result”] 时,调试器给我 nil,但我仍然通过条件并在记录,当它执行下一行时它崩溃 致命错误:在展开可选值时意外发现 nil 这是正常的,因为我尝试解开一个 nil 值!

但我确实发现如果我这样做:

var result : [String:AnyObject] = representation as! [String : AnyObject];
if result["result"] != nil {
    print("result = \(result["result"])")
    result = representation["result"] as! [String : AnyObject]
}

效果不错

我知道,我知道你们中的一些人会说:你们找到了解决方案,为什么要在 stackoverflow 上发帖—— 我这样做是因为我想了解为什么第一个解决方案不起作用,并且因为我的错误肯定不是特定于这种情况。

【问题讨论】:

    标签: ios swift casting anyobject


    【解决方案1】:

    您的代码无法编译,因为representation["result"] 导致

    错误:“下标”的使用不明确

    除此之外考虑改用if let

    if let res = result["result"] {
        print("result = \(res)")
        result = res as! [String : AnyObject]
    }
    

    除此之外,您还应该使用guards 使您的演员更安全:

    guard let result = representation as? [String : AnyObject] else {
        // not a suitable dictionary
        return
    }
    if let res = result["result"] {
        guard let resultDic = res as? [String : AnyObject] else {
            // not a suitable dictionary neither
            return
        }
        print(resultDic)
    }
    

    【讨论】:

    • 谢谢回复,我的代码正在编译,我不知道为什么它不能在你身边编译,实际上我曾经做过一个:if let result = (representation["result" ] ??表示)为? [String:AnyObject] 要检查,但为了我的解释,我想更笼统。我一直在寻找的答案来自 Hussein Alzand,当我比较时我需要在其中进行转换,所以最后我做 = if let result = ((representation["result"] as?[String:AnyObject]) ??representation) as ? [字符串:任何对象]
    • 抱歉,它确实可以编译!我没有接受你的回答,因为侯赛因解释说,演员阵容也必须在比较中完成。
    【解决方案2】:

    因为您必须在检查之前将representation["result"] 转换为字典,所以如果您输入representation["result"] as! [String : AnyObject],它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多