Kurtis Nusbaum Kurtis Nusbaum - 2 months ago 7
Swift Question

Using where clause in an if statement

I'm using the big nerd ranch's book to learn iOS programming in swift. One of their examples has me typing the following code:

if let text = textField.text where !text.isEmpty {
celsiusLabel.text = text
}
else {
celsiusLabel.text = "???"
}


This was working fine a few weeks ago, but now I've upgraded to swift 3 and it seems to have stopped compiling. What's the correct and idiomatic way to write this if statement?

Answer

This was tweaked as per Proposal SE-0099, Restructuring Condition Clauses, which was implemented in Swift 3.

if let text = textField.text, !text.isEmpty {
    celsiusLabel.text = text
}
else {
    celsiusLabel.text = "???"
}

The if statement is already in itself like a where clause, so they found it more suitable to just require a comma.

Comments