Skip to content

Instantly share code, notes, and snippets.

@MrSkwiggs
Last active April 16, 2020 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrSkwiggs/82eb119f235f63396cca40314ef423be to your computer and use it in GitHub Desktop.
Save MrSkwiggs/82eb119f235f63396cca40314ef423be to your computer and use it in GitHub Desktop.
?? Operator for multiple-optionals - Overloads that extends the default ?? operator behaviour up to triple optionals
//
// Created by Dorian Grolaux on 14/01/2020.
// Copyright © 2020 Skwiggs Inc. All rights reserved.
//
import Foundation
/**
Nil coalesces 2-level optionals in a single step
*/
func ??<T> (optional: T??, defaultValue: @autoclosure () throws -> T) rethrows -> T {
return try optional as? T ?? defaultValue()
}
/**
Nil coalesces 2-level optionals in a single step
*/
func ??<T> (optional: T??, defaultValue: @autoclosure () throws -> T?) rethrows -> T? {
return try optional as? T ?? defaultValue()
}
/**
Nil coalesces 3-level optionals in a single step
*/
func ??<T> (optional: T???, defaultValue: @autoclosure () throws -> T) rethrows -> T {
return try optional as? T ?? defaultValue()
}
/**
Nil coalesces 3-level optionals in a single step
*/
func ??<T> (optional: T???, defaultValue: @autoclosure () throws -> T?) rethrows -> T? {
return try optional as? T ?? defaultValue()
}
@MrSkwiggs
Copy link
Author

MrSkwiggs commented Jan 14, 2020

Examples

Double optional

Now

let a: Int?? = 8
let b = a ?? 10

Before

let a: Int?? = 8
let b = a as? Int ?? 10

Triple optionals

Now

let a: Int??? = 4
let b = a ?? 9

Before

let a: Int??? = 8
let b = (a as? Int?) as? Int ?? 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment