Saturday, March 28, 2015

Optionals

Declaring

// Use question mark to say this variable can be nil.
var myLastName: String?
myLastName = nil

// Check if nil (null)
if (myLastName == nil) {
    myLastName = "Moeykens"
}

// Using the Nil Coalescing Operator to get a value
let lastName = myLastName ?? "No last name found"
// Note: If myLastName is nil then "No last name found" is used.

Getting Value from Optional

Check for value using Optional Binding (if let)
if let lastName = myLastName {
    // It's guaranteed to have a value.
    print("Last name was found:\(lastName)") 
}
else {
    print("No last name found.")
}

Unwrapping

"Unwrap" or "Unwrapping" refers to getting a non-nil value of the optional. There are a few different ways to do this without having to write an if statement every time to check if a value exists.

// Force Unwrap with exclamation point
print(myLastName!) // This will generate an ERROR if myLastName is nil

// A different way might be to use a ternary conditional operator to avoid the error
let lastName = myLastName == nil ? "none" : myLastName
print(lastName)

// An even easier way is to use the Nil Coalescing Operator (??)
let lastName = myLastName ?? "none"
print(lastName)
// The Nil Coalescing Operator automatically unwraps the optional if there is a value

print(myLastName) // This will NOT generate an error if myLastName is nil
// Will just print: "nil"
(Updated for Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...