ios - plist 文件中的数组

标签 ios arrays swift dictionary

我有一个 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 从磁盘读取属性列表,而是使用 DataPropertyListSerialization

要按数字方式对字符串键进行排序,请使用 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/

相关文章:

ios - 试图实现 CLLocationManager : Getting compile time error

iphone - 外部类里面的KVO无法正常工作

javascript - 如何检查变量值是否包含在 JavaScript 数组中

ios - Swift:声音在模拟器上播放但不在设备上播放

ios - Swift UIView 内存使用和处理许多 subview

objective-c - iOS - UIView 边框底部宽度?

ios - 将 TitleLabel 从 UIButton 发送到不同 UIView Controller 中的 UILabel,但未发送

arrays - 如何消除matlab中比较操作的循环?

ios - 通过对象中包含的字典数组过滤对象数组

ios - swift 收听未选择的 GoogleMaps 标记