Search code examples
swiftoption-typeguard

swift - unwrapping optional with "guard let"


I am parsing JSON data. After I start getting unexpectedly found nil while unwrapping an Optional value errors. I tried to use guard statement.

But again I am getting the same error.

guard let articleTitle = self.articles?[indexPath.row]["title"].string! else {return}

I simulate nil value like this:

guard let articleTitle = self.articles?[indexPath.row]["t"].string! else {return}

What I am doing wrong?


Solution

  • It doesn’t make much sense to force unwrap the optional in a conditional let assingment. Remove the !:

    guard let articleTitle = self.articles?[indexPath.row]["title"].string else {return}
    

    Otherwise the right-hand side will never produce nil but crash.