Array from plist file

问题内容:

I have a plist file but a get disordered array from this file:

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

        if let array = NSDictionary(contentsOfFile: path){

          let list = Array(array.allKeys)
            print(list)

      }
    }

And result of print(list) is something look like this:

[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]

and I need array like [1,2,3,....30,31]

问题评论:

4  
Use the sorted() something like let list = Array(array.keys).sorted()
    
@ReinierMelian sorted() would not be available for [Any], you should cast it to [Int] 🙂 You could check my answer.
    
@AhmadF yes you are right but Another solution is casting the NSDictionary itself to [Int:Any]🙂 you could check my answer too

答案:

答案1:

Since you are getting the list from the plist, as an array successfully, all you have to do for sorting it is to use sorted() array instance method.

However, since you are reading the values from a plist file, the type of Array(array.allKeys) would be [Any], in order to be able to use the sorted() you have to cast it, like this:

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 should be be as the desired result.

答案评论:

答案2:

Another way to do this is casting the NSDictionary to [Int:Any] this allow you call the .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)

      }
    }

答案评论:

答案3:

First of all your question is a bit misleading. The result of print(list) cannot be an array of Int since all property list keys are required to be String.

Second of all, don’t use the NSDictionary related API to read a property list from disk, use Data and PropertyListSerialization instead.

To sort the string keys numerically use 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)

答案评论:

原文地址:

https://stackoverflow.com/questions/47751262/array-from-plist-file

添加评论

友情链接:蝴蝶教程