Search code examples
swiftdictionaryfoundation

Swift Dictionary Representation


I'm working on creating a Swift Dictionary out of some custom objects.

Below is where I define the dictionary; var carDictionary:[String:Any] = Dictionary<String, Any>()

The for loop below is where I'm trying to populate the dictionary out of my custom objects:

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

dataPoint is an instance of the following class:

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
    }
}

I'm getting what appears to be the admittedly somewhat common error of

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

However, I think there's some missing part of my understanding of how dictionary creation works in Swift that's keeping me from figuring out the issue - anyone have any suggestions? Thank you!

Posts with similar problems: 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


Solution

  • You're putting the value where it's expecting a key subscript.

    Similar to arrays, you access objects in your dictionary like this:

    let myValue = myDictionary["myKey"]
    

    This retrieves the object in the dictionary that had the key "myKey". To instead set a value in the dictionary, assign to the key subscript like this:

    myDictionary["myKey"] = myValue
    

    In your case, it looks like your dataPoint class has key and value objects that can be used in the dictionary:

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