Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String is not convertible from Dictionary<String,AnyObject> Error in Swift

Tags:

swift

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

like image 231
Chet Avatar asked Apr 25 '26 00:04

Chet


2 Answers

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)
like image 164
Leif Ashley Avatar answered Apr 26 '26 14:04

Leif Ashley


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 ]]
like image 35
Connor Avatar answered Apr 26 '26 13:04

Connor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!