Swift – Unwrap Optional Variable

To unwrap an optional variable in Swift, use exclamation mark ! character after the variable name in an expression.

The syntax to unwrap a variable x is

</>
Copy
x!

Examples

In the following program, we will define an optional integer variable, and unwrap it in an arithmetic expression.

main.swift

</>
Copy
var x : Int? = 25
let result = x! + 10
print(result)

Output

Swift - Unwrap Optional Variable

If value in this optional variable is nil, then using this optional variable causes runtime error.

main.swift

</>
Copy
var x : Int?
let result = x! + 10
print(result)

Output

Swift - Unwrap Optional Variable - Runtime Error

Conclusion

In this Swift Tutorial, we learned how to unwrap an optional variable in Swift programming.