簡體   English   中英

來自plist文件的數組

[英]Array from plist file

我有一個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]數組

由於您是從plist獲取list ,因此成功地將其作為一個數組,對其進行排序所需要做的就是使用sorted()數組實例方法。

但是,由於要從plist文件中讀取值,因此Array(array.allKeys)的類型為[Any] ,為了能夠使用sorted() ,必須將其 Array(array.allKeys) ,如下所示:

if let path = Bundle.main.path(forResource: "SomePlistFile", ofType: "plist"){
    if let array = NSDictionary(contentsOfFile: path){
        if let list = Array(array.allKeys) as? [Int] {
            let sortedList = list.sorted()

            print(sortedList)
        }
    }
}

sortedList應該是期望的結果。

另一種方法是將NSDictionary強制轉換為[Int:Any]這允許您調用.sorted()

if let path = Bundle.main.path(forResource: "SomePlistFile", ofType: "plist"){

        if let array = NSDictionary(contentsOfFile: path) as? [Int:Any]{

          let list = Array(array.keys).sorted()
          print(list)

      }
    }

首先,您的問題有點誤導。 由於所有屬性列表鍵都必須為String ,所以print(list)的結果不能為Int數組。

其次,不要使用與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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM