Swift Optionals and `nil`

This tutorial belongs to the Swift 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…


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

This tutorial belongs to the Swift 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:

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:

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:

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:

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

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

var value: Int? = 2

if let age = value {
    print(age)
}


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-06-07T05:00:00+00:00) Swift Optionals and `nil`. Retrieved from https://www.scien.cx/2021/06/07/swift-optionals-and-nil/

MLA
" » Swift Optionals and `nil`." flaviocopes.com | Sciencx - Monday June 7, 2021, https://www.scien.cx/2021/06/07/swift-optionals-and-nil/
HARVARD
flaviocopes.com | Sciencx Monday June 7, 2021 » Swift Optionals and `nil`., viewed ,<https://www.scien.cx/2021/06/07/swift-optionals-and-nil/>
VANCOUVER
flaviocopes.com | Sciencx - » Swift Optionals and `nil`. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/07/swift-optionals-and-nil/
CHICAGO
" » Swift Optionals and `nil`." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/06/07/swift-optionals-and-nil/
IEEE
" » Swift Optionals and `nil`." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/06/07/swift-optionals-and-nil/. [Accessed: ]
rf:citation
» Swift Optionals and `nil` | flaviocopes.com | Sciencx | https://www.scien.cx/2021/06/07/swift-optionals-and-nil/ |

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.