问题描述
我一直在玩弄斯威夫特。我曾与多个类型的错误,尤其是斯威夫特和我的老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'
我已经使用的尝试! [AnyObject]
但是,这将引发另一个错误:
But that throws another error:
AnyObject不是字典
我没有得到第二误差,因为这并不必须是一个亚型,但周围的其他方法。任何想法如何解决此问题?我没有找到答案了几个小时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
///协议,这是所有类都隐式遵循。
根据你想要做什么,你可能需要使用任何
在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!