Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to add dictionary arrays to an array?

Can I add dictionary arrays (is this the correct term for a dictionary key holding multiple values?) to an array?

var dictionary = [String: [String]]()
var array = [String]()

var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"

dictionary["3"] = [data1, data2, data3, data4, data5, data6]

var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"

dictionary["2"] = [data7, data8, data9, data10, data11, data12]

var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"

dictionary["1"] = [data13, data14, data15, data16, data17, data18]

I tried this:

array.extend([dictionary["1"], dictionary["2"], dictionary["3"]])

but there was an error "Cannot invoke 'extend' with an argument list of type '([[(String)?])"..

How do I add dictionary["1"], ["2"] & ["3"] accordingly into the array?

like image 348
Allister Bah Avatar asked Dec 08 '22 03:12

Allister Bah


2 Answers

Your array type declaration is not correct. Please try below one

var array: [[String:[String]] = []
like image 76
Santu C Avatar answered Dec 26 '22 08:12

Santu C


In case you are not interested in the order you might try:

array.extend(flatMap(dictionary.values, {$0}))

If order is important you might build your optionalArrays first:

let optionalArrays = [dictionary["1"], dictionary["2"], dictionary["3"]]
array.extend(flatMap(optionalArrays, {$0 ?? []}))

i.e. your dictionary returns an optional array, this causes the error you reported.

Hope this helps

like image 29
Matteo Piombo Avatar answered Dec 26 '22 10:12

Matteo Piombo