Skip to content

Instantly share code, notes, and snippets.

@patricklynch
Last active October 30, 2021 05:23
Show Gist options
  • Save patricklynch/689525d466c4ada42b8e to your computer and use it in GitHub Desktop.
Save patricklynch/689525d466c4ada42b8e to your computer and use it in GitHub Desktop.
The 6 ways to unwrap optionals in Swift 2.0
// The 6 ways to uwnrap optionals in Swift 2.0
//
// Created by Patrick Lynch on 6/28/15.
// Copyright © 2015 Patrick Lynch. All rights reserved.
import Foundation
// 1. Force Unwrapping
// 2. Optional Binding
// 3. Optional Chaining
// 4. Nil Coalescing
// 5. Switch-case
// 6. Guard
// 1. Force Unwrapping
var a: String? = "Hello"
let aForceUnwrapped = a!
print( aForceUnwrapped ) // Will crash if `a` is nil
// 2. Optional Binding
// Single binding
var b: String? = "Hello"
if let bUnwrapped = b {
print( "Unwrapped b: \(bUnwrapped)" )
}
// Multiple bidings with `where` clause
var b1: String? = "Hello 1!"
var b2: String? = "Hello 2!"
if let b1Unwrapped = b1, let b2Unwrapped = b1
where b2Unwrapped.characters.count > 0 && b1Unwrapped != b2Unwrapped {
print( "Unwrapped b1: \(b1Unwrapped)" )
print( "Unwrapped b2: \(b2Unwrapped)" )
}
if var bUnwrappedMutable = b1 {
bUnwrappedMutable += " World!"
print( "Unwrapped b1: \(bUnwrappedMutable)" )
}
var i = 0
var c: String? = "\(i)"
while let cUnwrapped = c {
print( "Unwrapped c: \(cUnwrapped)" )
if ++i >= 10 {
c = nil
}
}
// 3. Optional Chaining
struct B {
func doSomethingElse() { print( "B: Do Something Else" ) }
}
struct A {
var bOptional: B?
func doSomething() { print( "A: Do Something" ) }
}
let objectA: A? = A()
objectA?.doSomething() // Methods
let bProperty: B? = objectA?.bOptional // Properties
// Subscripts
var dictionary: [ String : String ]? = nil
dictionary?[ "myKey" ] = "myValue"
if let myValue = dictionary?[ "myKey" ] {
print( myValue )
}
// Closures
var myClosure: (()->())? = nil
myClosure?() // Only called if `myClosure` is not nil
// 4. Nil Coalescing
var d:String? = nil
let greeting1:String = d ?? "Hello"
d = "Guten Tag"
let greeting2:String = d ?? "Buongiorno"
print( "Greeating 1: \(greeting1), Greeating 2: \(greeting2)" )
// 5. Switch-case
enum Optional<T> { // Optionals are a generic enum like this
case Some(T)
case None
}
var e:AnyObject? = "e" // Change this value to see different results
switch e {
case .Some(let value as String) where value.characters.count == 1:
print( "String Value with length of 1: \(value)" )
case .Some(let value as String):
print( "String Value: \(value)" )
case .Some(let value):
print( "Unkonwn Value: \(value)" )
case .None:
print( "e is nil" )
}
// 6. Guard
func unwrapOrFail( f: String? ) {
guard let fUnwrapped = f else {
fatalError( "f is nil" )
}
print( "fUnwrapped: \(fUnwrapped)" )
}
unwrapOrFail( "Freak Out" ) // Call with `nil` for error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment