Happiehappie
Happiehappie

Reputation: 1074

Realm.io with AnyObject subscript

I'm about to implement Realm models in my Swift 2.0 app. However, once I pod install Realm. My AnyObject subscripts for my app will cause a compile error

Cannot subscript a value of type 'AnyObject' with an index of type 'String'

Cannot subscript a value of type 'RLMProperty' with an index of type 'String'

Conditional cast from 'RLMProperty' to 'AnyObject' always succeeds

But the thing is outlet is not supposed to be a RLMProperty in the first place

The following is my code

var campaigns = [AnyObject]()

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    let campaignCell = tableView.dequeueReusableCellWithIdentifier("campaignCell", forIndexPath: indexPath) as! CampaignTableViewCell
    
    let outlet: AnyObject = (self.campaigns[indexPath.section]["surveys"]!![indexPath.row])["outlet"]!!
    
    
    // Configure the cell...
    campaignCell.outletID.text = outlet["code"] as? String
    campaignCell.outletNameLabel.text = outlet["name"] as? String
    //campaignCell.outletAddressLabel.text = outlet["outlet"]!!["address"] as? String
    campaignCell.outletStatusLabel.text = (self.campaigns[indexPath.section]["surveys"]!![indexPath.row])["progress"]!!["name"] as? String
    
    campaignCell.outletStatusLabel.textColor = UIColor.colorWithHexString(((self.campaigns[indexPath.section]["surveys"]!![indexPath.row])["progress"]!!["color"] as? String)!)
    
    return campaignCell
}

Upvotes: 1

Views: 546

Answers (1)

Simon Rice
Simon Rice

Reputation: 1139

I encountered this error myself - the trick was simply not to use AnyObject when you wish to access properties via a subscript.

Chances are, your instance(s) of AnyObject is already a dictionary of some form. If you know your keys are all strings, simply cast your object to [String: AnyObject] - otherwise, use [NSObject: AnyObject]. There is also a lot of force unwrapping going on in your sample, which I'm afraid is just asking for crashes! So how would I re-write your sample?

if let campaign = self.campaigns[indexPath.section] as? [String: AnyObject],
    surveys = campaign["surveys"] as? [AnyObject],
    survey = surveys[indexPath.row] as? [String: AnyObject],
    outlet = survey["outlet"] as? [String: AnyObject] {

    // Set up your cell here

}  

Long story short, if-let is your friend! Nil checking and type casting in one!

Better still, map your dictionaries to classes/structs and enjoy the benefits of strong typing - there are plenty of third party Swift frameworks to make this much easier!

Upvotes: 0

Related Questions