2015-04-18 88 views
5

我一直在玩Swift。我有類型的多個錯誤,特別是使用Swift和我的舊Objective-C類。這個方法的問題是:我期待在Objective-C中由NSDictionarys組成的數組。如何在swift中將字典分配給AnyObject

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 

這將返回Swift中的Dictionaries(它是NSDictionaries)。但最後一行拋出我的錯誤:

Dictionary' is not identical to 'AnyObject'

我使用as! [AnyObject]

嘗試,但拋出另一個錯誤:

'AnyObject' is not a subtype of 'Dictionary'

我沒有得到第二個錯誤,因爲這不必是一個子類型,但相反。有關如何解決這個問題的任何想法?我沒有找到幾個小時的谷歌和研究的答案。

+0

VAR arrToReturn:[字符串:AnyObject] = []或VAR arrToReturn:[AnyObject] = [],如果你想返回AnyObjects的陣列 –

回答

7

Dictionary是斯威夫特一個結構,而AnyObject

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

取決於你想要做什麼,你可能想在你的代碼中使用Any,或投你的字典NSDictionary中使用as NSDictionary。您澄清後


編輯:

如果你分手了從字典本身的append通話,你看到一個更好的錯誤消息:

所以,這個問題是你的字典包含一些Optional值,但可選是一個結構,不能轉換成Obj-C。您可以通過將其轉換爲UIImage!AnyObject!(ImplicitlyUnwrappedOptional)或使用as!進行修復。

+0

如果我通過'var arrToReturn:[NSDictionary] = [] 這樣做了對於curArr中的obj { 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」]] as! NSDictionary) }, 我得到的錯誤:'不能調用'追加'類型的參數列表'(NSDictionary)'' – user2456014

+0

使用任何是不可能的,因爲這個方法是由Xcode生成的,不能改變,因爲它期望Objective-C代碼中的NSArray。 – user2456014

+1

您使用的是什麼版本的Xcode?這個對我有用。 – jtbandes

1

你的代碼在操場上工作正常,沒有編譯或運行時錯誤。下面是我加填充curArr

var curArr:[Dictionary<String, AnyObject>] = [ 
    [ 
     "imageName" : "photo.jpg", 
     "colorDic" : ["red" : 1.0, "green" : 0.0, "blue" : 0.0], 
     "percentage" : 0.5 
    ] 
] 

有了這一切迫使展開,我認爲你必須要確保什麼self.getItemsForCurrentStack()的回報確實是你所期望的。

結果在遊樂場:

[ 
"percentage": {Some 5.0e+-1}, 
"image": nil, 
"color": {Some r 1,0 g 0,0 b 0,0 a 1,0} 
] 

我的建議是要重構爲對象 - 這將使你的代碼,這樣更具有可讀性!

+0

問題不在於代碼,而是返回語句,返回arrToReturn,其中包含NSDictionaries或其他對象的數組。 – user2456014

0

在夫特3

code: 

var curArr:[Dictionary<String, Any>] = [ 
[ 
     "imageName" : "photo.jpg", 
     "colorDic" :[ 
      "red" : 1.0, 
      "green" : 0.0, 
      "blue" : 0.0 
     ], 
     "percentage" : 0.5 
    ] 
] 

enter image description here