Home > Enterprise >  How to get keys from Array of tuple in Swift
How to get keys from Array of tuple in Swift

Time:11-17

I am getting a dictionary [String: Int] from API, sorting it by value. In that, I am getting an Array of Tuple, in that array of tuple I need to separate the keys and want to make an array with that keys in that same sorted order.

I tried a way to get the object from that array and added it into a dictionary, but it is not working fine, because the dictionary is getting unordered while adding or after adding the keys, need help to resolve this issue

Tried code

let personalInfoDict = screenConfigResponse?.screenConfiguration?.personalInformation
let personalDict : [String : Int]?
if let dict = personalInfoDict, dict.count > 0 {
    personalDict = self.sortWithKeys(dict)
}

func sortWithKeys(_ dict: [String: Int]) -> [String: Int] {
    let sorted = dict.sorted(by: { $0.value < $1.value })
    var newDict: [String: Int] = [:]
    for sortedDict in sorted {
        newDict[sortedDict.key] = sortedDict.value
    }
    return newDict
}

When doing sort I got in a correctly sorted order, but when I loop and add it in newDict, it is going unordered, is there any way to get only the keys from the Array of tuples

CodePudding user response:

Maybe you can transform it to an array of tuple:

let personalInfoDict = screenConfigResponse?.screenConfiguration?.personalInformation
let personalPairs = personalInfoDict
    .reduce(into: [(String, Int)]()) { $0.append(($1.key, $1.value)) }
    .sorted(by: { $0.0 < $1.0 })

Now you have a [(String, Int)] ordered array

CodePudding user response:

For literature dictionaries, there is a type of HashTables. But HashTables are not ordered data structures, so the effect you get is expected behavior.

However, Apple provides an optional package that adds to your project other data structures (https://github.com/apple/swift-collections). In particular I think "OrderedDictionary" is your solution.

let baseDict : [String:Int] = ["Test1" : 5,
                                   "Test2" : 1,
                                   "Test3" : 4]

let orderedDict : OrderedDictionary<String, Int> = sortWithKeys(baseDict: baseDict)
print(orderedDict)

func sortWithKeys(baseDict : [String:Int]) -> OrderedDictionary<String, Int>
{
    let temp = baseDict.sorted(by: { $0.value < $1.value })
    var newDict : OrderedDictionary<String, Int> = [:]
    for element in temp {
        newDict[element.key] = element.value
    }
    return newDict
}
  • Related