ios - error using valueForKey in swift -
why error when used valueforkey
... using same trick in objectivec
...
in objectivec
, code
self.strsubscribe =[responseobject[@"subscribe"] valueforkey:@"subscribe_ids"];
in swift
, code
self.strsubscribe = responseobject["subscribe"].valueforkey["subscribe_ids"] as! string
i declare variables
var arraysubcategory : nsmutablearray! = nsmutablearray() var strsubscribe:string!
and tried access value below response
{ subscribe = { "subscribe_ids" = "1,14"; } }
edit works using amit , eric's solution following data
{ data = ( { "subscribe_ids" = "1,14"; } ); } let dictionary = responseobject["data"][0] as! dictionary<string,anyobject> self.strsubscribe = dictionary["subscribe_ids"] as! string
or//
if let dic = responseobject["data"][0] as? [string:string], let ids = dic["subscribe_ids"] { self.strsubscribe = ids }
but gives me error:
could not find member 'subscript'
swift doesn't know type of responseobject["subscribe"]
, have compiler bit; example:
if let dic = responseobject["subscribe"] as? [string:string], let ids = dic["subscribe_ids"] { self.strsubscribe = ids // "1,14" }
update:
it's still same problem: compiler doesn't know type of responseobject["data"]
, when try access subscript there's error (because you know it's dictionary inside array, compiler doesn't).
one solution give type compiler declaring array of dictionaries in if let
condition:
if let arr = responseobject["data"] as? [[string:string]], let ids = arr[0]["subscribe_ids"] { self.strsubscribe = ids }
notice it's [[string:string]]
(array of dictionaries), not [string:string]
(dictionary).
Comments
Post a Comment