尝试对字典进行排序,但结果又混淆了

问题描述 投票:0回答:1

尝试按此属性的键排序

let data: [String: [Interests]]
但保存数据后它再次混淆。我该如何解决这个问题。

这是结构模型

// MARK: - InterestsData
struct InterestsData: Codable {
   let message: String?
   let data: [String: [Interests]]


   func sortedByKey() -> InterestsData {
       let sortedKeys = data.keys.sorted()
    
       print("SORTED KEYS:",sortedKeys) // Sorted Alphabetically 
    
       var sortedData: [String: [Interests]] = [:]
            
       for key in sortedKeys {
           sortedData[key] = data[key]
       }
    
       print("SORTED KEYS WITH DATA ", sortedData) //Now keys not sorted
    
       return InterestsData(message: message, data: sortedData)
   }


}



// MARK: - Interests
   struct Interests: Codable {
       let id: Int
       let name: String
       let isSelected: Int?
   }
arrays swift dictionary sorting struct
1个回答
0
投票

由于字典是未排序的集合(无法排序),因此您只能使用自定义的KeyValuePairs数组:

import Foundation
import AppKit

struct InterestsData: Codable {
   let message: String?
   let data: [CustKeyValuePair<String, [Int]>]
    
   func sortedByKey() -> InterestsData {
       let sortedData = data.sorted(by: { $0.key < $1.key })
    
       return InterestsData(message: message, data: sortedData )
   }
}

struct CustKeyValuePair<T1, T2>: Codable where T1: Codable, T2: Codable {
    let key: T1
    var value: T2
}

////// TESTING of solution on real data:

let data = [
    "1asdf" : [1,2,3],
    "5asdf" : [1,2,3,4,5,6],
    "4asdf" : [1,2,3,1,2],
    "3asdf" : [1,2,3,2],
    "2asdf" : [1,2,3,0]
].map{ CustKeyValuePair(key: $0.key, value: $0.value) }

let a = InterestsData(message: "message", data: data )

let b = a.sortedByKey().data.map{ $0.key }

print(b)

控制台输出:

["1asdf", "2asdf", "3asdf", "4asdf", "5asdf"]
Program ended with exit code: 0

数据已排序

© www.soinside.com 2019 - 2024. All rights reserved.