Search code examples
swiftswift-playground

Swift: Converting


I am struggling with converting between formats for dictionaries: I am trying to convert the item array below into the result Array below. Essentially by looking for duplicates in the items first element and then only adding files to the result set when the first parameter is different.

var items:[[String]] = [["a", "b"],["a", "c"],["b", "c"]]

var result:[[String:[String]]] = [
    ["a":["b","c"]],
     ["b":["c"]]
]

I have tried using a multitude of arrays however I keep hitting errors in my xcode. Any idea what the best approach would be?

The for in loop always seems to come up one item short. Help would be much appreciated.


Solution

  • I'm assuming a general case where the sub arrays in item can have more than on string. This also allows for empty arrays in the items array. This gives results ["a": ["b", "c", "g"], "b": ["c"], "c": []]

    func testThree() {
        let items = [["a", "b"],["a", "c", "g"],["b", "c"],["c"]]
        var result:[String:[String]] = [:]
    
        for arr in items {
            if(arr.count > 0) {
                let first = arr[0]
                if(result[first] != nil) {
                    result[first]!.append(contentsOf: arr[1..<arr.count])
                } else {
                    result[first] = Array(arr[1..<arr.count])
                }
            }
        }
    }