-1

I am using this flatmap function to return a dictionary but it is returning [(key: String, value: String)] instead. What is the difference between [(key: String, value: String)] and a dictionary? Here is the code I am using. What would be the best way to do this. totalResponseArray is a custom class of type Array<Duplet<Product, imageArray>>.

let sizeDict  = totalResponseArray.flatMap { (obj) -> [String:String] in
        var storedItem = [String:String]()
        storedItem["\(obj.one.productID)"] = "\(obj.one.size)"
        return storedItem
    }

The other way I can think to do this is using a loop but I feel like there is a cleaner way to do it.

I am trying to apply a flatmap function to an array not a dictionary. The result of the flatmap function should be a dictionary of [String:String].

Here is the result I am trying to get. Is there a better or cleaner way of doing it? I figured out that the above code doesn't make sense to get this same result as the code below.

var storedItem = [String:String]()

    for eachItem in totalResponseArray{
        storedItem["\(eachItem.one.productID)"] = "\(eachItem.one.color)"
    }

EDIT: It turns out that the loop is the best way and only way to do it. I am not trying to map the function.

Nevin Jethmalani
  • 2,726
  • 4
  • 23
  • 58
  • I don't think it is a duplicate. I am trying to apply a Flatmap function to an array not a dictionary. The result of the flatmap function should be a dictionary. – Nevin Jethmalani Jun 24 '17 at 16:30
  • Sorry, my fault. – However, [What's the cleanest way of applying map() to a dictionary in Swift?](https://stackoverflow.com/questions/24116271/whats-the-cleanest-way-of-applying-map-to-a-dictionary-in-swift) should be helpful, as it explains the difference between a Dictionary and an array/sequence of key/value pairs. I strongly assume that similar methods can be applied here. – Martin R Jun 24 '17 at 16:34
  • Maybe give us some sample input plus your expected result to avoid misunderstandings. – shallowThought Jun 24 '17 at 16:43
  • I am trying to get a dictionary of [String:String] from an array of custom class. Basically I am looking to loop through the array of custom class and update a dictionary with values for each item in that array. So for each productId, I want to assign a color essentially. – Nevin Jethmalani Jun 24 '17 at 16:58

1 Answers1

3

[(key: String, value: String)] is not a Dictionary but an Array of tuples of type (key: String, value: String).

shallowThought
  • 19,212
  • 9
  • 65
  • 112