我想把这些词按重量分类。怎么做?
//这是字典
let words: [String:AnyObject] = [
"a" : [["name":"apple", "weight": "2"],["name" : "ant", "weight": "1"],["name": "animal", "weight": "3"]],
"b" : [["name":"bat", "weight": "4"],["name" : "ball", "weight": "2"],["name": "blue", "weight": "1"]],
"c" : [["name":"cat", "weight": "6"],["name" : "cow", "weight": "5"],["name": "crown", "weight": "8"], ["name": "camel", "weight": "7"]],
"d" : [["name":"dog", "weight": "3"],["name" : "donkey", "weight": "2"]],
"e" : [["name":"elephant", "weight": "2"],["name":"egg", "weight": "4"],["name":"e", "weight": "3"]]
]
谢谢
最佳答案
这里有一个更好的解决方案,可以很好地将数据存储在Item
结构中。这样处理容易多了
struct Item {
let name: String
let weight: Int
}
let items = [ //has type [String : [Item]]
"a" : [
Item(name: "apple", weight: 2),
Item(name: "ant", weight: 1),
Item(name: "animal", weight: 3),
],
"b" : [
Item(name: "bat", weight: 4),
Item(name: "ball", weight: 2),
Item(name: "blue", weight: 1),
],
"c" : [
Item(name: "cat", weight: 6),
Item(name: "cow", weight: 5),
Item(name: "crown", weight: 8),
Item(name: "camel", weight: 7),
],
"d" : [
Item(name: "dog", weight: 3),
Item(name: "donkey", weight: 2),
],
"e" : [
Item(name: "elephant", weight: 2),
Item(name: "egg", weight: 4),
Item(name: "e", weight: 3),
]
]
for (firstLetter, itemArray) in items {
items[firstLetter] = itemArray.sort{$0.weight < $1.weight} //"sorted" in Swift 3
}
print(sortedItems)
关于swift - 根据特定参数对单词词典进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38081022/