Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
let unread = 3
if unread {
print("new mail")
} else {
print("no mail")
}It does not compile
- Expecting
new mailbecause a non-zero number counts as true, as in C or JavaScript. In Swift a condition must be aBool; writeunread != 0. - Expecting the program to stop only when it reaches the
ifline. The compiler checks the condition's type before the program starts, so nothing runs.
- How would you rewrite the condition so the program prints
new mail? - Which kinds of expressions can stand as the condition of an
ifin Swift?