0

I've run into a problem, and I can not find a solution. I have an array where I store the start x and end x locations of different objects

placedArray : [[String: [Int: [String: String]]]]

placedArray = [["auto": [0: ["x-start": "300", "x-end": "400"]]], ["bus": [0: ["x-start": "0", "x-end": "300"]]]]

I want to add one more auto to the list, so what I try to do is:

placedArray["auto"].append([1: ["x-start": "400", "x-end": "500"]])

Error:

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

I would like to get at the end

placedArray = [["auto": [0: ["x-start": "300", "x-end": "400"], 1: ["x-start": "300", "x-end": "400"]]], ["bus": [0: ["x-start": "0", "x-end": "300"]]]]
1
  • 1
    You have an array of dictionaries. Array can only be subscripted with an integer, you subscripted it with a string. Anyhow, time to define a struct or a class instead of shoving everything into a dictionary Commented Nov 21, 2017 at 15:33

1 Answer 1

1

Two issues:

  • The outer object is an array, so it must be subscripted with Int index (that's the statement of the error message).
  • The value for key auto is a dictionary, so you cannot append something.

You have to get the first item of placedArray – which is the auto entry – and then set the value for key 1.

var placedArray : [[String: [Int: [String: String]]]]
placedArray = [["auto": [0: ["x-start": "300", "x-end": "400"]]], ["bus": [0: ["x-start": "0", "x-end": "300"]]]]
placedArray[0]["auto"]?[1] = ["x-start": "400", "x-end": "500"]
print(placedArray)

The line to append 😉 the value can also be written as

placedArray[0]["auto"]?.updateValue(["x-start": "400", "x-end": "500"], forKey: 1)

Nevertheless this kind of nested array / dictionary is very confusing. How about a (very simple) struct based solution:

struct XValue { let start, end : String }

struct Vehicle {
    let name : String
    var xValues : [XValue]

    mutating func add(xValue : XValue) {
        xValues.append(xValue)
    }
}

var placedArray = [Vehicle(name: "auto", xValues: [XValue(start:"300", end: "400")]),
                   Vehicle(name: "bus", xValues: [XValue(start:"0", end: "300")])]

placedArray[0].add(xValue: XValue(start:"400", end: "500"))
print(placedArray)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.