gpt4 book ai didi

arrays - 如何按键对 Dictionary 进行排序,其中值是 Swift 4 中的对象数组?

转载 作者:搜寻专家 更新时间:2023-11-01 06:15:00 25 4
gpt4 key购买 nike

我有一个字典,其中包含 String 键和 Objects 数组作为值。使用 append 方法将这些值从已排序的对象数组添加到字典中。这些值根据对象属性的首字母分类为键。但返回未排序的字典。

字典被声明为:

var namesDic = [String: [Name]]()

var filteredNames = [String: [Name]]()

遍历数组并追加到字典中:

for name in names {
let letterIndex = name.getName().index(name.getName().startIndex, offsetBy: 0)

let letter = name.getName()[letterIndex]

if namesDic[String(letter)] != nil {
namesDic[String(letter)]?.append(name)
} else {
namesDic[String(letter)] = [name]
}
}
filteredNames = namesDic

}

名称结构:

struct Name {
var id: Int!
var name: String!
var native: String!
var meaning: String!
var origin: String!
var isFavorite: Bool
var gender: String!

init(id: Int, name: String, native: String, meaning: String, origin: String, isFavorite: Int, gender: String) {
self.id = id
self.name = name
self.native = native
self.meaning = meaning
self.origin = origin
if isFavorite == 0 {
self.isFavorite = false
} else { self.isFavorite = true }
self.gender = gender
}
}

我在调试中发现,当它们附加到字典时,它们是未排序的。我知道 Swift Dictionary 上的排序不起作用,但我想要解决方法来按键对 Dictionary 进行排序以将其传递给 TableView。

我在这里经历了很多问题/答案,但它们都是针对 [String: String] 而不是 Array of Objects

最佳答案

struct Name: CustomStringConvertible {
let id: Int
let name: String
let native: String
let meaning: String
let origin: String
let isFavorite: Bool
let gender: String
var description: String {
return "Id: " + String(id) + " - Name: " + name
}
}

let name1 = Name(id: 1, name: "Tim Cook", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")
let name2 = Name(id: 2, name: "Steve Jobs", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")
let name3 = Name(id: 3, name: "Tiger Woods", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")
let name4 = Name(id: 4, name: "Socrates", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")

let names = [name1, name2, name3, name4]


let dictionary = names.sorted(by: {$0.name < $1.name }).reduce(into: [String: [Name]]()) { result, element in
// make sure there is at least one letter in your string else return
guard let first = element.name.first else { return }
// create a string with that initial
let initial = String(first)
// initialize an array with one element or add another element to the existing value
result[initial, default: []].append(element)
}

let sorted = dictionary.sorted {$0.key < $1.key}
print(sorted) // "[(key: "S", value: [Id: 4 - Name: Socrates, Id: 2 - Name: Steve Jobs]), (key: "T", value: [Id: 3 - Name: Tiger Woods, Id: 1 - Name: Tim Cook])]\n"

关于arrays - 如何按键对 Dictionary 进行排序,其中值是 Swift 4 中的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com