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

时间:2018-01-29 13:59:23

标签: arrays swift nsarray nsdictionary plist

我试图获取plist中所有键的所有项目的组合。

使用下面的代码我分别得到了键的值,但我可以得到他们的项目,但是当用户点击index = 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]]
}

1 个答案:

答案 0 :(得分:0)

我做了什么,保留了你逻辑的大部分内容:
使用" keypaths"
数组 然后迭代所有keyPath,追加每个"子阵列的内容"到最后的阵列。

Use suggested solution要从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