Optionals in Swift 3

Swift Optionals

A type the either has a “wrapped” value or is nil.

let imagePaths = ["star": "/glyphs/star.png","portrait": "/images/content/portrait.jpg","spacer": "/images/shared/spacer.gif"]

Getting a dictionary’s value using a key returns an optional value, so imagePaths[“star”] has the type String?

 if let imagePath = imagePaths["star"]
 print("The star image is at '(imagePath)'")
 print("Couldn't find the image")

would print “The star image is at ‘/glyphs/star.png'”
but “if let starPath = imagePaths[puppy]…..
would print “Couldn’t find the image”
To safely access the properties and methods of a wrapped instance, use the postfix optional chaining operator (postfix ?).

if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
 print("The star image is in PNG format")
// Prints "The star image is in PNG format"

if you want to supply a “default” value for when the optional is nil, use the nil-coalescing operator (??)

let defaultImagePath = "/images/default.png"
let imagePath = imagePaths["puppy"] ?? defaultImagePath
// Prints "/images/default.png"

Unconditionally Unwrapping
When you’re certain that an optional contains a value, you can unconditionally unwrap it using the forced unwrap operator (!)

let number = Int("42")!
// Prints "42"

Automatic Unwrapping
If you declare an optional variable with a ! instead of a ? it will automatically unwrap.

var myString:String?
myString = "Hello, Swift!"
if myString != nil {
 println( myString! )
 }else {
 println("myString has nil value")


var myString:String!
myString = "Hello, Swift!"
if myString != nil {
 }else {
 println("myString has nil value")

NOTE: Unconditionally unwrapping a nil instance with ! triggers a runtime error.
see more at https://developer.apple.com/documentation/swift/optional

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s