Skip to content

Instantly share code, notes, and snippets.

@ncooke3
Created July 28, 2019 05:55
Show Gist options
  • Save ncooke3/795021304d2659a5cab3af1fe756c43c to your computer and use it in GitHub Desktop.
Save ncooke3/795021304d2659a5cab3af1fe756c43c to your computer and use it in GitHub Desktop.
Examples of the ways to unwrap optional values
import UIKit
var optionalString: String? // can be i.e "hello" or nil
// method 1️⃣: if let
if let string = optionalString {
print("I have a value. I am \(string)")
} else {
print("I do not have a value yet- I am nil!")
}
// method 2️⃣: guard
func doubleNumber(num: Int?) {
guard let number = num else {
print("number is nil! We will exit function!")
return
}
print("My doubled value is \(number * 2)")
}
doubleNumber(num: nil) // guard statement will catch this and exit!
doubleNumber(num: 5) // guard statement will let this pass and print the double number
// method 3️⃣: force unwrap
let forcedString: String?
//forcedString! // errors because forcedString is not yet initialized!
let forcedInt: Int?
forcedInt = 5
forcedInt! // doesn't error because we had assigned 5 to forcedInt
let nonOptionalInt = 5
//nonOptionalInt! // errors because you cant force unwrap a non-optional value! Basically, we
// assigned nonOptionalInt to 5 from the start, so it could never
// have possibily been nil!
// method 4️⃣: optional chaining
struct Tree {
var type: String
var height: Int
var hasLeaves: Bool
}
var maple: Tree? //maple has not been initialized yet!
let mapleHasLeaves = maple?.hasLeaves // unwraps maple to get hasLeaves value
// hasLeaves can be nil
// In this case maple.hasLeaves is nil, but trying to
// access the property won't cause our code to crash
// because we are using an optional (?)
//print(mapleHasLeaves) // prints 'nil'
if let hasLeaves = mapleHasLeaves {
print("maple has leaves: \(hasLeaves)")
} // we could provide an 'else {}' right here!
// method 5️⃣: nil-coalescing operator -> a ?? b
// the nil-coalescing operator (??) is shorthand for
let a: Int? = 5 // a is an optional int since we will later force unwrap it
// It must be optional since and we cant unwrap a non-optional!
let b: Int = 0
a != nil ? a! : b // a ?? b (behind the scenes!)
// think of b as the default value
// We are basically saying, if a isnt nil, then force unwrap its value!
// If a is nil, then let's use b's value
print(a) //prints 5 since a has value
let c: Int? = nil
c ?? b // nothing crazy here... we are using the nil-coalescing operator
// instead of the long form we used with a & b
print(c) // c's value was nil so we used b's value
// We still print nil though...tbh i need to figure that out...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment