2017-05-06 48 views
0

我正在創建Swift Dictionary以外的一些自定義對象。Swift詞典表示法

下面是我定義字典的地方; var carDictionary:[String:Any] = Dictionary<String, Any>()

的下面循環就是我試圖填充字典我的自定義對象:

for dataPoint in dataPoints! { 
    carDictionary[dataPoint.value(forKey: dataPoint.dataKey)] 
} 

dataPoint是下面的類的實例:

public class NACarDataPoint: NSObject { 

    var dataKey: String! 
    var dataValue: Any! 

    public override init() { 
     // generic initializer, generally designed to be overridden 
     super.init() 
    } 

    init(key: String, value: Any) { 
     self.dataKey = key 
     self.dataValue = value 
    } 
} 

我我得到了似乎是公認的普遍錯誤

`Cannot subscript a value of type `[String : Any]` with an index of type `Any`?` 

但是,我認爲我對Swift中字典創建的工作原理有些遺漏,這讓我無法理解這個問題 - 任何人都有什麼建議?謝謝!

帖子有類似問題: String not convertible to [AnyObject]

Cannot subscript a value of type '[String : String]?' with an index of type 'String'

Cannot subscript a value of [AnyObject]? with an index of type Int

回答

0

你把在那裏的期待鍵標值。

到數組類似,您訪問的對象在你的字典裏是這樣的:

let myValue = myDictionary["myKey"] 

這檢索在有鑰匙「的myKey」字典對象。要改爲設置在字典中的值,分配給該鍵標這樣的:

myDictionary["myKey"] = myValue 

在你的情況下,它看起來像你的數據點類有可能在字典中使用的鍵和值對象:

for dataPoint in dataPoints! { 
    carDictionary[dataKey] = dataPoint.value(forKey: dataPoint.dataKey) 
}