Swift 3 - 从 plist 的所有数组中获取所有项目

Swift 3 - Get all items from all arrays from plist

我正在尝试获取 plist 中所有键的所有项目的组合。

使用下面的代码,我分别获取键的值,我可以获得它们的项目,但是当用户单击索引 = 0 的单元格时,我想显示所有项目

这是 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]]
}

我会做什么,保留你的大部分逻辑:
使用 "keypaths"
的数组 然后对所有 keyPath 进行迭代,将每个 "subarray" 的内容附加到最终数组。

从 plist 读取,因为从 Swift3+ 开始,我们倾向于尽可能避免使用 NSDictionary/NSArray(所有 NS 东西)。

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