Swift 3 - 按数组索引访问项目键值
Swift 3 - Access item key values by array index
您好,我正在尝试访问我的 plist 中 legs 数组中的项目
我希望能够从这个 plist
的腿数组中获取 key = "title" 的值
我已经有了从名为 abs 的字典中获取值的方法,它是以下代码
let path = Bundle.main.path(forResource:"Exercise", ofType: "plist")
let dict:NSDictionary = NSDictionary(contentsOfFile: path!)!
if (dict.object(forKey: "levels") != nil) {
if let levelDict:[String : Any] = dict.object(forKey: "levels") as? [String : Any] {
for (key, value) in levelDict {
if ( key == "something") {
print(value)
}
}
}
}
但是我不知道如何访问 legs 数组来获取项目标题
所以我设法找到了我最初问题的答案
let path = Bundle.main.path(forResource: "Exercise", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)!
let levelArray:AnyObject = dict.object(forKey: "legs")! as AnyObject
if let nsArray:NSArray = levelArray as? NSArray{
var levelDict:AnyObject = nsArray[1] as AnyObject //currentLevel is an Int
//then finally I could get data from a dictionary in the array
let Title = levelDict["title"] as AnyObject? as! String
print(Title)
}
所以现在这将打印 legs 数组中的第二项,即 "leg 2"
在到达 [[String:String]]
类型的 legs 数组时,在您的情况下具有三个元素,每个索引具有两个键对值。您可以遍历该索引并获取您的值,然后迭代到其他索引。
let yourLegsArray:AnyObject = dict.object(forKey: "legs")! as AnyObject
然后迭代 yourLegsArray
并获取 Dict
.
的内部值
您好,我正在尝试访问我的 plist 中 legs 数组中的项目 我希望能够从这个 plist
的腿数组中获取 key = "title" 的值我已经有了从名为 abs 的字典中获取值的方法,它是以下代码
let path = Bundle.main.path(forResource:"Exercise", ofType: "plist")
let dict:NSDictionary = NSDictionary(contentsOfFile: path!)!
if (dict.object(forKey: "levels") != nil) {
if let levelDict:[String : Any] = dict.object(forKey: "levels") as? [String : Any] {
for (key, value) in levelDict {
if ( key == "something") {
print(value)
}
}
}
}
但是我不知道如何访问 legs 数组来获取项目标题
所以我设法找到了我最初问题的答案
let path = Bundle.main.path(forResource: "Exercise", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)!
let levelArray:AnyObject = dict.object(forKey: "legs")! as AnyObject
if let nsArray:NSArray = levelArray as? NSArray{
var levelDict:AnyObject = nsArray[1] as AnyObject //currentLevel is an Int
//then finally I could get data from a dictionary in the array
let Title = levelDict["title"] as AnyObject? as! String
print(Title)
}
所以现在这将打印 legs 数组中的第二项,即 "leg 2"
在到达 [[String:String]]
类型的 legs 数组时,在您的情况下具有三个元素,每个索引具有两个键对值。您可以遍历该索引并获取您的值,然后迭代到其他索引。
let yourLegsArray:AnyObject = dict.object(forKey: "legs")! as AnyObject
然后迭代 yourLegsArray
并获取 Dict
.