2017-02-09 45 views
0

我正在尝试读取字典中所有索引的值。我一次只能抓取一个索引。如何在swift中从字典中获取所有索引值?

var monster: Monster! 

monster.moves![0]["move_id"] as? Int ?? 0 

这让我抓住索引中的第一项。但我正在阅读一个SQLite数据库,并需要匹配值。

for user in try! db.prepare(Table("moves").where(id == (monster.moves![0]["move_id"] as? Int ?? 0) && damage_class == (monster.moves![0]["move_id"] as? Int ?? 0))) { } 

它只会检查id是否与monster.moves匹配!在第一个索引处,而不是检查所有的索引。我需要获取move_id等于某个数字的值。我怎么能做到这一点?

回答

0

您可以通过这种方式从字典中获取所有值。

for value in yourDictionary.values.array { 
    print("\(value)") 
} 
0

这是可能的,这可能需要一些调整,因为我没有太多的代码的熄灭的:

let monsterArray = monster.values.filter { $0["move_id"] == id && $0["move_id"] == damage_class } 

在英语中,这需要您monster字典,访问的阵列它包含的所有values,然后根据{ }括号中指定的内容进行过滤。结果将保存在monsterArray常数中。

随着monsterArray,你可以执行任何你需要对付这些值的行动。

使用这种方法也会比for循环快得多,因为您不需要遍历每个可能的值。

0

试试这个

如果你的怪物物体移动属性不是NSArray的类型,然后将其转换成NSArray的类型

if let movesArray : NSArray = monster.moves as! NSArray 
{ 
    let idsArray = movesArray.valueForKey("move_id") as! [Int] // change it to your required type array 
} 

有你现在去,你有idsArray移动IDS,现在你可以做你想用这些ID做什么。

0

您需要索引所有字典的值,请试试。我希望它的工作

for index in 0...monster.moves.count-1{ 

    for user in try! db.prepare(Table("moves").where(id == (monster.moves![index]["move_id"] as? Int ?? 0) && damage_class == (monster.moves![index]["move_id"] as? Int ?? 0))) 
    { 
     //Whatever you want to do 
    } 
}