Unwrapping optional array from return function

Hey guys,

The code below parses json data returned from a website. What is the best way to unwrap the optional array instead of using forced-unwrap ?

func parseData(data:Data)-> [Articles] {
var articles: [Articles]? =

    do {
        let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

        let jsonArticles = jsonResult?["articles"] as! [AnyObject]

        for jsonArticle in jsonArticles{
            let article = Articles()
            article.author = jsonArticle["author"] as? String
            article.title = jsonArticle["title"] as? String
            article.urlToImage = jsonArticle["urlToImage"] as? String
            article.publishedAt = jsonArticle["publishedAt"] as? String
            articles?.append(article)
        }


     } catch {
        print("Nothing my guy(error)")
    }
  return articles
}

It's usually easiest to coalesce into an empty array in situations like this.

let jsonArticles = jsonResult?["articles"] as? [AnyObject] ?? []

(May require parens around the cast.)

However, what you really want to do here is to create an Article type that adopts Decodable which you then use to parse your JSON using JSONDecoder.

Terms of Service

Privacy Policy

Cookie Policy