Chet
Chet

Reputation: 19849

String is not convertible from Dictionary<String,AnyObject> Error in 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

Upvotes: 3

Views: 3166

Answers (2)

Leif Ashley
Leif Ashley

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

Connor
Connor

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

Related Questions