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

时间:2016-08-18 17:17:00

标签: ios arrays swift sorting pfobject

我直接从Parse拉出一系列字典并将它们显示在表格中。所以我真的很想处理我手中的数据结构(下面奇怪的结构化词典)。

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

由于我对数据模型没有很多控制权,并且它在整个应用程序中的使用受到限制,我更倾向于专注于算法解决方案而不是结构化。 / p>

我提出了一种方法来做到这一点,但它似乎效率低下而且速度慢,我确定有人可以做得更好。

//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

谢谢!

4 个答案:

答案 0 :(得分:7)

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数组的末尾,但它们的相对顺序是不确定的。

答案 1 :(得分:6)

要求

所以你有一系列词典。

let dictionaries: [[String:AnyObject?]] = [
    ["Name" : "Frank", "Age" : 32],
    ["Name" : "Bill"],
    ["Age" : 18],
    ["Name" : "Susan", "Age" : 47]
]

您想要对数组进行排序:

  • Name值升序
  • 没有Name String的词典应该在最后

解决方案

这里是代码(函数式编程样式中的

let sorted = dictionaries.sort { left, right -> Bool in
    guard let rightKey = right["Name"] as? String else { return true }
    guard let leftKey = left["Name"] as? String else { return false }
    return leftKey < rightKey
}

输出

print(sorted)

[
    ["Name": Optional(Bill)],
    ["Name": Optional(Frank), "Age": Optional(32)],
    ["Name": Optional(Susan), "Age": Optional(47)],
    ["Age": Optional(18)]
]

答案 2 :(得分:0)

创建一个数据类型来表示您的数据:

struct Person 
{
    let identifier: String
    let name: String?
    let age: Int?
}

进行提取程序:

func unpack(objects: [[String : Any]]) -> [Person]
{
    return objects.flatMap { object in

        guard let identifier = object["ObjectID"] as? String else {
            // Invalid object
            return nil
        }
        let name = object["Name"] as? String
        let age = object["Age"] as? Int

        return Person(identifier: identifier, name: name, age: age)
    }
}

您的数据类型可以按其字段排序,因为它们具有真实类型。

let objects: [[String : Any]] = 
               [["ObjectID" : "1", "Name" : "Frank", "Age" : 32],
                ["ObjectID" : "2", "Name" : "Bill"],
                ["ObjectID" : "3", "Age" : 18],
                ["ObjectID" : "4", "Name" : "Susan", "Age" : 47]]

let persons = unpack(objects)

let byName = persons.sort { $0.name < $1.name }

nil比较&#34;之前&#34;任何其他价值;你可以编写自己的比较器,如果你想改变它。

答案 3 :(得分:-1)

这是我要做的。如果你能够,我会通过给它一个名称和年龄而不仅仅是键和值来使结构更具体。这应该为您提供如何实现这一目标的大纲!

struct PersonInfo {
    var key: String!
    var value: AnyObject?

    init(key key: String, value: AnyObject?) {
        self.key = key
        self.value = value
    }
}

class ViewController: UIViewController {
    var possibleKeys: [String] = ["Name", "Age", "ObjectId"]
    var personInfos: [PersonInfo] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        for infos in json {
            for key in possibleKeys {
                if let value = infos[key] {
                    personInfos.append(PersonInfo(key: key, value: value))
                }
            }
        }
        personInfos.sortInPlace({$0.value as? Int > $1.value as? Int})
    }
}

让这更容易,在这里:

struct PersonInfo {
    var key: String!
    var objectId: Int!
    var name: String?
    var age: Int? 

    init(key key: String, objectId: Int, name: String?, age: Int?) {
        self.key = key
        self.objectId = objectId
        self.name = name
        self.age = age
    }
}

class ViewController: UIViewController {
    var possibleKeys: [String] = ["Name", "Age", "ObjectId"]
    var personInfos: [PersonInfo] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        for infos in json {
            var objectId: String!
            var name: String? = nil
            var age: Int? = nil
            for key in possibleKeys {
                if let value = infos[key] {
                    if key == "ObjectId" {
                        objectId = value as? String
                    }
                    if key == "Name" {
                        name = value as? String
                    }
                    if key == "Age" {
                        age = value as? Int
                    }
                }
            }
            personInfos.append(PersonInfo(key: key, objectId: objectId, name: String?, age: Int?))
        }
        //by objectId
        personInfos.sortInPlace({$0.objectId? > $1.objectId?})

        //by age
        personInfos.sortInPlace({$0.age? > $1.age?})

        //byName
        personInfos.sortInPlace({$0.name?.compare($1.name?) == NSComparisonResult.OrderedAscending})
    }
}