Search code examples
arraysswiftnsarraynsdictionaryplist

Swift 3 - Get all items from all arrays from plist


I'm trying to get a combination of all the items for all the keys in the plist.

With the code below I am getting the values for keys separately and I can get their items however when user clicks on the cell where index = 0 I want to show all the items

This is the plist

func loadPlist()->[[String:String]] {

    let path = Bundle.main.path(forResource: "myText", ofType: "plist")
    let dict = NSDictionary(contentsOfFile: path!)!
    var keyPath = ""


    if muscleIndex == 0{
        //Show values from all keys here
    }
    else if muscleIndex == 1{
        keyPath = "abs"
    }
    else if muscleIndex == 2{
        keyPath = "arms"
    }
    else if muscleIndex == 3{
      keyPath = "back"
    }
    else if muscleIndex == 4{
        keyPath = "chest"
    }
    else if muscleIndex == 5{
        keyPath = "shoulders"
    }
    else if muscleIndex == 6{
        keyPath = "legs"
    }


    let levelArray:AnyObject = dict.object(forKey: keyPath)! as AnyObject
    let nsArray:NSArray = (levelArray as? NSArray)!


    return nsArray as! [[String : String]]
}


Solution

  • What I'd do, keeping most part of your logic:
    Use an array of "keypaths"
    Iterate then for all keyPath, appending the content of each "subarray" to the final array.

    Use suggested solution to read from plist because from Swift3+ we tend to avoid using NSDictionary/NSArray (all NS stuff) whenever possible.

    var keyPaths = [String]()
    
    if muscleIndex == 0 {
        keyPaths.append("abs")
        keyPaths.append("arms")
        ... (you can append all of them in one line too)
    }
    else if muscleIndex == 1 {
        keyPaths.append("abs")
    }
    else if ...
    
    
    var returnArray = [[String:String]]()
    if let filePath = Bundle.main.path(forResource: "plistTest", ofType: "plist")
    {
    
        let fileURL = URL.init(fileURLWithPath: filePath)
        if let plistData = try? Data.init(contentsOf: fileURL)
        {
            let topLevel = try! PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as! [String:Any]
            for aKeyPath in keyPaths {
                let subArray = topLevel[aKeyPath] as! [[String:String]]
                returnArray.append(contentsOf: subArray)
            }
        }
    }
    return returnArray