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
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)
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 ]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With