I have the following code. the response.result.value
is of type Optional(AnyObject)
, I want to check
it's of type [[String: AnyObject]]
unwrap the optional
check the count of the array
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?
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With