Reputation: 19849
I've been battling this for too long. I have no idea
var a : [[String:AnyObject]] = [
[
"this":12
]
]
var b = "this"
func findAllKV(array: [[String:AnyObject]], key: String, value: AnyObject) -> [[String:AnyObject]] {
var all : [[String:AnyObject]] = []
for dict in array {
if dict[key] == value {
all.append(dict)
}
}
return all
}
findAllKV(a, b, 12)
I'm just trying to make a function that searches though an array of dictionaries and finds all with the matching key value
Upvotes: 3
Views: 3166
Reputation: 275
Try this one - println() helps reveal the issue:
var a : [[String:AnyObject]] = [
[
"this":12,
"test":13
],
[
"me":15,
"you":16
]
]
var b = "you"
func findAllKV(array: [[String:AnyObject]], key: String, value: AnyObject) -> [[String:AnyObject]] {
var all : [[String:AnyObject]] = []
for dict in array {
println(dict)
println(dict[key])
if let value: AnyObject = dict[key] {
println(value)
all += dict
}
}
return all
}
findAllKV(a, b, 12)
Upvotes: 2
Reputation: 64654
dict[key] returns an optional value. Try unwrapping it before checking:
var a : [[String:AnyObject]] = [
[
"this":12
]
]
var b = "this"
func findAllKV(array: [[String:AnyObject]], key: String, value: AnyObject) -> [[String:AnyObject]] {
var all : [[String:AnyObject]] = []
for dict in array {
if let val: AnyObject = dict[key] {
if val === value {
all.append(dict)
}
}
}
return all
}
var x = findAllKV(a, b, 12)
println(x) //[[this : 12 ]]
Upvotes: 1