gpt4 book ai didi

ios - Swift 按键排序字典数组,其中值是可选的 AnyObject

转载 作者:IT王子 更新时间:2023-10-29 05:49:00 27 4
gpt4 key购买 nike

我直接从 Parse 中提取一系列字典并将它们显示在表格中。所以我真的很想使用我收到的数据结构(下面结构奇怪的字典)。

A PFObject[String : AnyObject?] 并且我希望能够按任意键排序,所以我不知道对象类型和键可能某些词典中没有。因为在 Parse 中,如果你不给一个属性一个值,它就根本不存在。例如:

[
{
"ObjectId" : "1",
"Name" : "Frank",
"Age" : 32
},
{
"ObjectId" : "2",
"Name" : "Bill"
},
{
"ObjectId" : "3",
"Age" : 18
}
{
"ObjectId" : "4",
"Name" : "Susan",
"Age" : 47
}

]

我希望缺少键的字典总是排在排序后的字典之后。一个例子:

原始表:

ObjectId   Name       Age
1 Frank 32
2 Bill
3 18
4 Susan 47

按名称排序:

ObjectId   Name       Age
2 Bill
1 Frank 32
4 Susan 47
3 18

由于我对数据模型没有太多控制权,而且它在整个应用程序中的使用受到限制,所以我更愿意专注于算法解决方案而不是结构性解决方案。

我想出了一个方法来做到这一点,但它似乎效率低下且缓慢,我确信有人可以做得更好。

//dataModel is an array of dictionary objects used as my table source
//sort mode is NSComparisonResult ascending or descending
//propertyName is the dictionary key

//first filter out any objects that dont have this key
let filteredFirstHalf = dataModel.filter({ $0[propertyName] != nil })
let filteredSecondHalf = dataModel.filter({ $0[propertyName] == nil })

//sort the dictionaries that have the key
let sortedAndFiltered = filteredFirstHalf { some1, some2 in

if let one = some1[propertyName] as? NSDate, two = some2[propertyName] as? NSDate {
return one.compare(two) == sortMode
} else if let one = some1[propertyName] as? String, two = some2[propertyName] as? String {
return one.compare(two) == sortMode
} else if let one = some1[propertyName] as? NSNumber, two = some2[propertyName] as? NSNumber {
return one.compare(two) == sortMode
} else {
fatalError("filteredFirstHalf shouldn't be here")
}
}

//this will always put the blanks behind the sorted
dataModel = sortedAndFiltered + filteredSecondHalf

谢谢!

最佳答案

Swift 无法比较任何两个对象。您必须先将它们转换为特定类型:

let arr: [[String: Any]] = [
["Name" : "Frank", "Age" : 32],
["Name" : "Bill"],
["Age" : 18],
["Name" : "Susan", "Age" : 47]
]

let key = "Name" // The key you want to sort by

let result = arr.sort {
switch ($0[key], $1[key]) {
case (nil, nil), (_, nil):
return true
case (nil, _):
return false
case let (lhs as String, rhs as String):
return lhs < rhs
case let (lhs as Int, rhs as Int):
return lhs < rhs
// Add more for Double, Date, etc.
default:
return true
}
}

print(result)

如果有多个字典没有指定key的值,它们将被放在result数组的末尾,但它们的相对顺序是不确定的。

关于ios - Swift 按键排序字典数组,其中值是可选的 AnyObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39024013/

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