Search code examples
iosswiftplist

Swift: Reading plist - How to filter by key and read and append value only


Swift 3

I'm trying to read a plist file to update my array for collection view.

My menu.plist has 6 items that I want to read and append to my array that uses .count to update the collection view.

Problem is I'm having trouble sorting the dictionary. I want to append the strings in value to my array but sort the transfer by the key which has the text "Item 0", "Item 1", etc. Because the array comes unorganized which makes it harder to use the switch statements on didSelectItemAt.

In the code I'm not using key only appending value to mainGroup array but its unorganized and I need to filter it by the plist key

Code in ViewDidLoad

var mainGroup = [String]()

var myDict: NSDictionary?
if let path = Bundle.main.path(forResource: "menu", ofType: "plist") {
    myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {

    print(dict)

    for (_, value) in dict {

        mainGroup.append("\(value)")
    }

    print(mainGroup)
}

Plist

pic 1


Solution

  • You need sort your dict.keys array and the access to value by those sorted keys

    Full code

    var mainGroup = [String]()
    
        var myDict: [String:String]?
        if let path = Bundle.main.path(forResource: "menu", ofType: "plist") {
            myDict = NSDictionary(contentsOfFile: path) as? [String:String]
        }
        if let dict = myDict {
    
            print(dict)
    
            for key in dict.keys.sorted() {
    
                mainGroup.append(dict[key]!)
            }
    
    
    
            print(mainGroup)
        }
    

    update

    Using array as @rmaddy says

    enter image description here

        var mainGroup = [String]()
    
        var myArray: [String]?
        if let path = Bundle.main.path(forResource: "menu", ofType: "plist") {
            myArray = NSArray(contentsOfFile: path) as? [String]
        }
    
        print(myArray)