serdar aylanc serdar aylanc - 1 year ago 76
Swift Question

swift - unwrapping optional with "guard let"

I am parsing

data. After I start getting
unexpectedly found nil while unwrapping an Optional value
errors. I tried to use

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?

Answer Source

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.