简体   繁体   English

Swift 2 Type Cast字典

[英]Swift 2 Type casting Dictionaries

I have this code in Swift 1.2: 我在Swift 1.2中有以下代码:

self.publicDatabase!.performQuery(query, inZoneWithID: nil) {
            results, error in
            if error != nil {
                NotificationUtility.postNotification(Notify.CloudKitVenuesRetrieveFailed, userinfo: ["result":results, "error":error])
            }
            else
            {
                NotificationUtility.postNotification(Notify.CloudKitVenuesRetrieveSuccess, userinfo: ["result":results])
            }
        }

But in Swift 2.0 this yields several compiler errors: 但是在Swift 2.0中,这会产生一些编译器错误:

"Type of expression is ambiguous without more context" “表达类型不明确,没有更多上下文”

and

"Cannot convert value of type '[String : [CKRecord]?]' to expected argument type '[NSObject : AnyObject]?'" “无法将类型'[String:[CKRecord]?]'的值转换为预期的参数类型'[NSObject:AnyObject]吗?'”

I know how to fix it to make the error go away, but it seems very ugly and hacky: 我知道如何修复它以使错误消失,但它看起来非常丑陋和hacky:

self.publicDatabase!.performQuery(query, inZoneWithID: nil) {
            results, error in
            if error != nil {
                NotificationUtility.postNotification(Notify.CloudKitVenuesRetrieveFailed, userinfo: ["result":results as! AnyObject, "error":error as! AnyObject])
            }
            else
            {
                NotificationUtility.postNotification(Notify.CloudKitVenuesRetrieveSuccess, userinfo: ["result":results as! AnyObject])
            }
        }

Is there a better way than having to go through every item in the dictionary and force downcast it to "AnyObject"? 是否有比必须遍历字典中的每个项目并将其强制向下转换为“ AnyObject”更好的方法?

You never want to cast down to AnyObject. 您永远不想将其转换为AnyObject。 My guess here is that your fix works because you're unwrapping an optional, not because you're casting to AnyObject. 我的猜测是,您的修复程序之所以有效,是因为您展开了一个可选的内容,而不是因为您正在投射到AnyObject。 I'm guessing, because I don't know what type results and error actually are, but this will likely work: 我猜是因为我不知道结果和错误实际上是什么类型,但这可能会起作用:

self.publicDatabase!.performQuery(query, inZoneWithID: nil) {
        results, error in
        if error != nil {
            NotificationUtility.postNotification(Notify.CloudKitVenuesRetrieveFailed, userinfo: ["result":results!, "error":error!])
        }
        else
        {
            NotificationUtility.postNotification(Notify.CloudKitVenuesRetrieveSuccess, userinfo: ["result":results!])
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM