Append whole row to 2d array

Asked by At

I'm trying to append a whole row to data .. the full example is actual a dict of 2d arrays:

  1> var a: [String:[[Double]]] = [:] 
a: [String : [[Double]]] = 0 key/value pairs
  2> a["a"] = []
  3> a["a"].append([0.1, 0.2])
error: repl.swift:3:2: error: value of type '[[Double]]?' has no member 'append'
a["a"].append([0.1, 0.2])
~^~~~~ ~~~~~~

How do I get ["a":[[0.1, 0.2], [0.2, 0.3]]] given that I will not know in advance what the key "a" is, nor the count of rows nor their values, until various later points in execution?

2 Answers

1
rmaddy On Best Solutions

Since a["a"] returns an optional (because there might not be the key "a" in the dictionary), you need to use a["a"]?.append([0.1, 0.2]).

Another option is to provide a default:

a["a", default: []].append([0.1, 0.2])

This even eliminates the need for the a["a"] = [] line.

1
Justin Block On

The reason you’re getting the error is you’re trying to append to an optional. Change it to a[“a”]?.append([0.1, 0.2])

For the expected output you would do

var a: [String: [[Double]]] = [:]

a["a"] = []
a["a"]?.append([0.1, 0.2])
a["a"]?.append([0.2, 0.3])

And another way to do it

var a: [String: [[Double]]] = [:]

a["a"] = [[0.1, 0.2], [0.2, 0.3]]