Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 warning: Non-optional expression of type 'String' used in a check for optionals

I'm updating a project to Swift 3 and came across the following warning which I can't seem to resolve.

fileprivate var filteredTitlesList: [String] = []

if let filteredTitle: String = filteredTitlesList[indexPath.row] as String { // 'Non-optional expression of type 'String' used in a check for optionals'

  // Do something

}

The answer to a similar question here didn't help me: Non-optional expression of type 'AnyObject' used in a check for optionals

Thanks a lot!

like image 355
nontomatic Avatar asked Nov 30 '16 09:11

nontomatic


2 Answers

You are trying to unwrap a value that is already unwrapped, and hence you are getting an error because it doesn't need unwrapping again. Change your if statement to look like the following and you should be golden:

if filteredTitleList.count > indexPath.row {
    let filteredTitle = filterdTitleList[indexPath.row]
}

Unfortunately there is no way to bind the variable within the if statement, hopefully they'll add one in the future.

like image 98
Jacob King Avatar answered Oct 12 '22 10:10

Jacob King


Other possibility of this warning is when you're trying to put a statement eg:let keyboardFrame: CGRect = keyboardFrameValue.cgRectValue in conditional statement like if or guard

like image 39
Ali Avatar answered Oct 12 '22 11:10

Ali