swift - 排序 plist 数据

标签 swift dictionary property-list

我在 plist 中有一些重复数据,然后将其提取到字典中并在我的应用程序中显示。唯一的问题是它需要与我在 plist 中的顺序相同,但显然,字典无法排序并且它未排序。那么我该如何实现呢?

我的plist数据是这样重复的

enter image description here

然后我将其转换为 [Int : ItemType] 类型的字典,ItemType 是我的数据协议(protocol),如下所示:

class ExhibitionUnarchiver {
    class func exhibitionsFromDictionary(_ dictionary: [String: AnyObject]) throws -> [Int : ItemType] {
        var inventory: [Int : ItemType] = [:]
        var i = 0;

        print(dictionary)

        for (key, value) in dictionary {
            if let itemDict = value as? [String : String],
            let title = itemDict["title"],
            let audio = itemDict["audio"],
            let image = itemDict["image"],
            let description = itemDict["description"]{
                let item = ExhibitionItem(title: title, image: image, audio: audio, description: description)
                inventory.updateValue(item, forKey: i);
                i += 1;
            }
        }

        return inventory
    }
}

这会导致像这样的字典:

[12: App.ExhibitionItem(title: "Water Bonsai", image: "waterbonsai.jpg", audio: "exhibit-audio-1", description: "blah blah blah"), 17: App.ExhibitionItem.....

我希望自从我创建了 key 的 Int 之后我就可以对其进行排序,但到目前为止我还没有运气。您可能会说我是 swift 的新手,所以请提供您认为相关的任何信息。谢谢!

最佳答案

字典没有顺序。如果您需要特定的顺序,请创建 Array 类型的 root:

enter image description here


或手动按键排序:

var root = [Int:[String:String]]()
root[1] = ["title":"Hi"]
root[2] = ["title":"Ho"]

let result = root.sorted { $0.0 < $1.0 }

print(result)

打印:

[(1, ["title": "Hi"]), (2, ["title": "Ho"])]

关于swift - 排序 plist 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444838/

相关文章:

swift - 在 Swift 中重置 CoreImage 过滤器

python - 如何从字典的字典中绘制分组条形图

python 代码在一个文件上有效,但在其他文件上失败

ios - 具有 NSNumber 到 NSString 映射的 NSDictionary 是非属性列表对象

swift - 如何在Swift中使用animationDidStop

ios - 在子类中根据 UIButton 大小设置 cornerRadius 的最佳位置?

来自 lldb 中记录的异常的 Swift stackframe 符号未被分解

excel - 在 VBA 中按键对字典进行排序

ios - iPhone:sqlite3 blob字段未正确反序列化