swift - Cannot get first(where:) to work with [NSDictionary] -
i have array of nsdictionary's , want dictionary out of array specific key "id". tried following error:
cannot call value of non-function type 'nsdictionary?'
consider following example of trying do:
let dictionaries: [nsdictionary] = [nsdictionary(dictionary: ["id": "123", "name": "the name"]), nsdictionary(dictionary: ["id": "456", "name": "the other name"])] if let dictionary = dictionaries.first(where: { $0.objectforkey("id") == "123" }) { print(event.objectforkey("name") ?? "") }
the problem result of objectforkey (object(for:) in swift 3). nsdictionary, has no types, result any?. cannot compare any? string. cast string needed:
if let dictionary = dictionaries.first(where: { $0["id"] as? string == "123" }) { print(dictionary["name"] ?? "") } the error message not make sense though.
you can avoid problem if use swift dictionary, or better, parse dictionaries structs/classes , work classes. never use dictionaries represent objects in app outside of decoding/encoding.
Comments
Post a Comment