Quickly how to deploy an extra and cast type at the same time using

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

  • this is type [[String: AnyObject]]
  • expand optional
  • check the number of arrays
  • I prefer one line guard 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"] } } 

Error article["content"] line,

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

Also I need to check if title exists in article ? Maybe he will collapse or just do nothing?

+5
source share
1 answer

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

You cannot put that (at compile time) declared by AnyObject into the String property.

Just replace it

 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 file will discard articles in which the title and content values ​​are incorrect. 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 } } 
+2
source

Source: https://habr.com/ru/post/1239755/


All Articles