# Swift conditionals: the if statement

> Learn how to use if and else conditionals in Swift, write boolean conditions cleanly, and why Swift prevents the bug of assigning instead of comparing.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-05-22 | Topics: [Swift](https://flaviocopes.com/tags/swift/) | Canonical: https://flaviocopes.com/swift-conditionals-if/

> This tutorial belongs to the [Swift](https://flaviocopes.com/swift-introduction/) 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:

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

An `else` block is executed if the condition is false: 

```swift
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:

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

And you can also just write:

```swift
if condition {
    // runs if `condition` is `true`
}
```

or 

```swift
if !condition {
    // runs if `condition` is `false`
}
```

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:

```swift
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.
