Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unwrap Swift optional and cast type at the same time using guard?

Tags:

ios

swift

I have the following code. the response.result.value is of type Optional(AnyObject), I want to check

  1. it's of type [[String: AnyObject]]

  2. unwrap the optional

  3. check the count of the array

  4. I prefer one line guard over if...return... statement

    Alamofire.request(.GET, API.listArticle).responseJSON { response in
        print(response.result.value)
    
        guard let articles = response.result.value as? [[String: AnyObject]] where articles.count > 0 else {
            return
        }
    
        for article in articles {
            let entity = NSEntityDescription.insertNewObjectForEntityForName("Article", inManagedObjectContext: DBHelper.context()) as! Article
            entity.title = article["title"]
            entity.content = article["content"]
    
        }
    }
    

The error is article["content"] line:

Cannot subscript a value of type Dictionary<String, AnyObject> with an index of type String

Also do I need to check if title exist in article? Is it gonna crash or just do nothing?

like image 258
OMGPOP Avatar asked Jan 04 '16 01:01

OMGPOP


1 Answers

The problem is that you are using a dictionary where the value has type AnyObject to populate the title and the content properties that are probably String (right?)

You cannot put something that (at compile time) is declared AnyObject into a String property.

Just replace this

entity.title = article["title"]
entity.content = article["content"]

with this

entity.title = article["title"] as? String
entity.content = article["content"] as? String

Update

This updated for will discard articles where the title and content values are not correct Strings.

for article in articles {

     if let
         title = article["title"] as? String,
         content = article["content"] as? String {

         let entity = NSEntityDescription.insertNewObjectForEntityForName("Article", inManagedObjectContext: DBHelper.context()) as! Article

         entity.title = title
         entity.content = content
     }
}
like image 139
Luca Angeletti Avatar answered Sep 28 '22 09:09

Luca Angeletti