# Swift optionals and nil

> Learn how optionals and nil work in Swift, how to declare an optional with a question mark, and how to safely unwrap its value using an if let statement.

Author: Flavio Copes | Published: 2021-06-07 | Canonical: https://flaviocopes.com/swift-optionals-nil/

> This tutorial belongs to the [Swift](https://flaviocopes.com/swift-introduction/) series

Optionals are one key feature of Swift.

When you don't know if a value will be present or absent, you declare the type as an optional. 

The optional wraps another value, with its own type. Or maybe not.

We declare an optional adding a question mark after its type, like this:

```swift
var value: Int? = 10
```

Now value is not an Int value. It's an optional wrapping an Int value.

To find out if the optional wraps a value, you must **unwrap** it.

We do so using an exclamation mark:

```swift
var value: Int? = 10
print(value!) //10
```

Swift methods often return an optional. For example the `Int` type initializer accepts a string, and returns an Int optional:

![Swift code showing Int("37") returns Optional<Int> type when converting string to integer](https://flaviocopes.com/images/swift-optionals-nil/Screen_Shot_2020-11-02_at_18.08.48.png)

This is because it does not know if the string can be converted to a number.

If the optional does not contain a value, it evaluates as `nil`, and you cannot unwrap it:

![Swift code showing Int("test") returns nil and crashes when force unwrapped with exclamation mark](https://flaviocopes.com/images/swift-optionals-nil/Screen_Shot_2020-11-02_at_18.12.13.png)

`nil` is a special value that cannot be assigned to a variable. Only to an optional:

![Swift code showing optional variable assigned nil and comparison returning true](https://flaviocopes.com/images/swift-optionals-nil/Screen_Shot_2020-11-02_at_18.14.21.png)

![Swift compiler error showing nil cannot be assigned to non-optional Int type](https://flaviocopes.com/images/swift-optionals-nil/Screen_Shot_2020-11-02_at_18.13.56.png)

You typically use `if` statements to unwrap values in your code, like this:

```swift
var value: Int? = 2

if let age = value {
    print(age)
}
```
