如何在词典中迅速分配到AnyObject [英] How to assign a Dictionary to AnyObject in swift

查看:193
本文介绍了如何在词典中迅速分配到AnyObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩弄斯威夫特。我曾与多个类型的错误,尤其是斯威夫特和我的老Objective-C类的工作。这种方法的问题是:我期待在Objective-C制成NSDictionarys数组

I have been playing around with Swift. I have had multiple errors with types, especially working with Swift and my old Objective-C classes. The problem with this method is: I am expecting an array made of NSDictionarys in Objective-C.

var curArr:[Dictionary<String, AnyObject>] = self.getItemsForCurrentStack()
var arrToReturn:[(Dictionary<String, AnyObject?>)] = []
for obj in curArr{
    arrToReturn.append(["image": UIImage(named: obj["imageName"] as! String), "color": UIColor(red:obj["colorDic"]!["red"] as! CGFloat, green:obj["colorDic"]!["green"] as! CGFloat, blue:obj["colorDic"]!["blue"] as! CGFloat, alpha:1.0), "percentage": obj["percantage"]])
}
return arrToReturn

这将返回斯威夫特字典(这是NSDictionaries)。但最后一行抛出我一个错误:

This returns Dictionaries (which are NSDictionaries) in Swift. But the last line throws me an error:

字典不是完全相同'AnyObject'

Dictionary' is not identical to 'AnyObject'

我已经使用的尝试! [AnyObject]

但是,这将引发另一个错误:

But that throws another error:

AnyObject不是字典

'AnyObject' is not a subtype of 'Dictionary'

我没有得到第二误差,因为这并不必须是一个亚型,但周围的其他方法。任何想法如何解决此问题?我没有找到答案了几个小时googleing和研究的。

I don't get the second error, since this doesn't have to be a subtype, but the other way around. Any ideas on how to solve this? I didn't find an answer for several hours of googleing and researching.

推荐答案

词典是斯威夫特一个结构,而 AnyObject

Dictionary is a struct in Swift, whereas AnyObject is

///协议,这是所有类都隐式遵循。

/// The protocol to which all classes implicitly conform.

根据你想要做什么,你可能需要使用任何在code或投你的字典NSDictionary中使用作为的NSDictionary

Depending what you're trying to do, you may want to use Any in your code, or cast your dictionary to NSDictionary using as NSDictionary.

你的澄清后编辑:

如果你分割了从字典本身追加通话,你看到一个更好的错误消息:

If you split up the append call from the dictionary itself, you see a better error message:

所以,问题是,你的字典包含一些可选值,但可选的是一个结构,而不是转换为的OBJ-C。您可以通过转换成 UIImage的修复! AnyObject!(ImplicitlyUnwrappedOptional),或使用如!

So, the issue is that your dictionary contains some Optional values, but Optional is a struct and not convertible to Obj-C. You can fix by casting to UIImage! and AnyObject! (ImplicitlyUnwrappedOptional), or by using as!.

这篇关于如何在词典中迅速分配到AnyObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆