Swift Conditionals: `if`

This tutorial belongs to the Swift series

if statements are the most popular way to perform a conditional check. We use the if keyword followed by a boolean expression, followed by a block containing code that is ran if the condition is tru…


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

This tutorial belongs to the Swift series

if statements are the most popular way to perform a conditional check. We use the if keyword followed by a boolean expression, followed by a block containing code that is ran if the condition is true:

let condition = true
if condition == true {
    // code executed if the condition is true
}

An else block is executed if the condition is false:

let condition = true
if condition == true {
    // code executed if the condition is true
} else {
    // code executed if the condition is false
}

You can optionally wrap the condition validation into parentheses if you prefer:

if (condition == true) {
    // ...
}

One thing that separates Swift from many other languages is that it prevents bugs caused by erroneously doing an assignment instead of a comparison. This means you can’t do this:

if condition = true {
    // The program does not compile
}

and the reason is that the assignment operator does not return anything, but the if conditional must be a boolean expression.


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-05-22T05:00:00+00:00) Swift Conditionals: `if`. Retrieved from https://www.scien.cx/2021/05/22/swift-conditionals-if/

MLA
" » Swift Conditionals: `if`." flaviocopes.com | Sciencx - Saturday May 22, 2021, https://www.scien.cx/2021/05/22/swift-conditionals-if/
HARVARD
flaviocopes.com | Sciencx Saturday May 22, 2021 » Swift Conditionals: `if`., viewed ,<https://www.scien.cx/2021/05/22/swift-conditionals-if/>
VANCOUVER
flaviocopes.com | Sciencx - » Swift Conditionals: `if`. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/22/swift-conditionals-if/
CHICAGO
" » Swift Conditionals: `if`." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/05/22/swift-conditionals-if/
IEEE
" » Swift Conditionals: `if`." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/05/22/swift-conditionals-if/. [Accessed: ]
rf:citation
» Swift Conditionals: `if` | flaviocopes.com | Sciencx | https://www.scien.cx/2021/05/22/swift-conditionals-if/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.