Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

error using valueForKey in swift

Why do I get an error when I used valueForKey... I am using same trick like in objectiveC ...

In ObjectiveC, the code is

self.strSubscribe =[responseObject[@"subscribe"] valueForKey:@"subscribe_ids"]; 

In Swift , the code is

self.strSubscribe = responseObject["subscribe"].valueForKey["subscribe_ids"] as! String  

I declare the variables like

var arraySubCategory : NSMutableArray! = NSMutableArray()
var strSubscribe:String!  

And I tried to access the value from below response

 { 
     subscribe = 
            {
               "subscribe_ids" = "1,14";
            }

 }

Edit It works using Amit and Eric's solution but now for 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 it gives me error:

could not find member 'subscript'

Upvotes: 1

Views: 1248

Answers (2)

Eric Aya
Eric Aya

Reputation: 70118

Swift doesn't know the type of responseObject["subscribe"], you have to help the compiler a bit; for example:

if let dic = responseObject["subscribe"] as? [String:String], let ids = dic["subscribe_ids"] {
    self.strSubscribe = ids  // "1,14"
}

UPDATE:

It's still the same problem: the compiler doesn't know the type of responseObject["data"], so when you try to access the subscript there's an error (because you know it's a dictionary inside the array, but the compiler doesn't).

One solution is to give the type to the compiler by declaring an array of dictionaries in the if let condition:

if let arr = responseObject["data"] as? [[String:String]], let ids = arr[0]["subscribe_ids"] {
    self.strSubscribe = ids  
}

Notice that it's [[String:String]] (array of dictionaries), not [String:String] (dictionary).

Upvotes: 2

Amit89
Amit89

Reputation: 3000

Write like this.

let dictionary = responseObject["subscribe"] as! Dictionary<String, AnyObject>
self.strSubscribe = dictionary["subscribe_ids"] as! String

Since responseObject["subscribe"] will give a AnyObject? output and AnyObject does not have any member called valueForKey.

Upvotes: 0

Related Questions