我有一个 plist 文件,但从此文件中获取无序数组:
if let path = Bundle.main.path(forResource: "SomePlistFile", ofType: "plist"){
if let array = NSDictionary(contentsOfFile: path){
let list = Array(array.allKeys)
print(list)
}
}
print(list) 的结果如下所示:
[9, 25, 18, 10, 26, 19, 11, 27, 12, 1, 28, 20, 13, 2, 29, 21, 14, 3, 4, 22, 15, 5, 6, 30, 23, 16, 7, 31, 24, 17, 8]
我需要像[1,2,3,....30,31]这样的数组
最佳答案
首先你的问题有点误导。 print(list)
的结果不能是 Int
数组,因为所有属性列表键都必须是 String
。
其次,不要使用 NSDictionary
相关 API 从磁盘读取属性列表,而是使用 Data
和 PropertyListSerialization
。
要按数字方式对字符串键进行排序,请使用 localizedStandardCompare
let url = Bundle.main.url(forResource: "SomePlistFile", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let list = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
let sortedList = list.keys.sorted{ $0.localizedStandardCompare($1) == .orderedAscending }
print(sortedList)
关于ios - plist 文件中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47751262/