我的词典包含字符串键和对象数组作为值。使用追加方法将这些值从已排序的对象数组添加到词典中。根据对象属性的第一个字母将值分类为键。但是返回未排序的Dictionary。
宣布词典:
var namesDic = [String: [Name]]()
var filteredNames = [String: [Name]]()
迭代数组并追加到Dictionary:
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]
而不是对象数组。
答案 0 :(得分:3)
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"
答案 1 :(得分:1)
根据Apple的文档
字典存储相同类型的键之间的关联 没有定义排序的集合中相同类型的值。每 value与唯一键相关联,该唯一键充当标识符 字典中的那个值。 与数组中的项目不同,中的项目 字典没有指定的顺序。你使用字典 当你需要根据他们的标识符查找值时 同样的方式,使用真实世界的字典来查找 特定单词的定义。
有关详情,请参阅Apple's Website
解决方法强>
可以做的一件事是创建一个排序键数组,然后使用该数组来访问字典值