Home > Net >  How to convert [Dictionary<String, Any>] to [String: Any] in swift
How to convert [Dictionary<String, Any>] to [String: Any] in swift

Time:11-08

I am sorting the array of dictionary able to do it below is the code but the out form is in

[Dictionary<String, Any>.Element]

I want in [String: Any] how to do it

func sortWithTableColumn(datavalue:[[String : Any]]) -> [[String : Any]]{
        var allresult2 = [[Dictionary<String, Any>.Element]]()
        for dict in datavalue{
            let sortedrow = dict.sorted(by: { $0.key < $1.key })
            allresult2.append(sortedrow)
            
        }}

Thanks In advance

CodePudding user response:

The problem is:

Swift’s Dictionary type is an unordered collection. The order in which keys, values, and key-value pairs are retrieved when iterating over a dictionary is not specified.

So if you try convert Array of Tuples into Dictionary after sorting:

var newDict = [String : Any]
for (key, value) in sortedrow {
   newDict[key] = value
}

You get no-sorted dictionary. Again. Instead of this you can try use Class or Struct:

struct SomeStruct {
    var key: String
    var someType: Any
}

Then convert your [Dictionary<String, Any>] to [[SomeStruct]]:

func sortWithTableColumn(datavalue:[[String : Any]]) -> [[SomeStruct]] {
    var allresult2 = [[SomeStruct]]()
        for dict in datavalue {
            let sortedrow = dict.sorted(by: { $0.key < $1.key })
            
            var newArray = [SomeStruct]()
            for (key, value) in sortedrow {
                newArray.append(SomeStruct(key: key, someType: value))
            }

            allresult2.append(newArray)
        }
    return allresult2
}

//test [Dictionary<String, Any>]
let dictionary = [
["a": 2, "k": 4, "b": 3, "l": 3, "c":7], 
["b": 3, "a": 2, "k": 4, "c":7, "l": 3]]

let sortedArray = sortWithTableColumn(datavalue: dictionary)

//print sorted array of arrays from SomeStructs
print(sortedArray) 
//print key from sorted array of arrays from SomeStructs
print(sortedArray[0][0].key)
  • Related