Search code examples
iosarraysswiftplist

Swift: How to read multiple array within array in plist?


This is my plist

Collections View

pic1

With Swift 3, I'm reading the plist to fill my arrays with this code perfectly but I do not know how to access the plist when it has arrays inside the root array

The code I use to read when the root is an array

var mainGroup = [String]()

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

mainGroup = myArray!

But in this plist, theres more arrays to read than just the root. I would like to read how many arrays the root has so in my collection view I use it in numberOfItemsInSection, cellForItemAt and didSelectItemAt. And I would like to also read items inside the arrays to display it in detail view of the collections for when an item is selected.

Conclusion: I want to read how many arrays are in root array to use it in .count and how to access the items in the arrays to display it in another view controller as detail. To access an array it would be array[2] but how would that work if I wanted to display the string "Jeans" and "4" , etc. Thank you


Solution

  • The recommended way in Swift to read a property list file is PropertyListSerialization. It avoids the usage of Foundation NSArray.

    The code prints the section numbers and all items in the inner array.

    If the property list is is supposed to populate a table view I recommend to declare the inner array as dictionary.

    let url = Bundle.main.url(forResource:"items", withExtension: "plist")!
    do {
        let data = try Data(contentsOf:url)
        let sections = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[Any]]
    
        for (index, section) in sections.enumerated() {
            print("section ", index)
            for item in section {
                print(item)
            }
        }
    } catch {
        print("This error must never occur", error)
    }