Skip to content

Instantly share code, notes, and snippets.

@tehprofessor
Last active August 29, 2015 14:23
Show Gist options
  • Save tehprofessor/48200b35c55dcb8fdfd6 to your computer and use it in GitHub Desktop.
Save tehprofessor/48200b35c55dcb8fdfd6 to your computer and use it in GitHub Desktop.
GetOrElse -- Swift
//
// GetOrElse.swift
//
// Requires Swift 2.0 for protocol extensions
//
import Foundation
protocol GetOrElse {
func getOrElse<T>(block block: () -> T) -> T
func getOrElse<T>(defaultValue: T) -> T
}
extension Optional : GetOrElse {
func getOrElse<T>(block block: () -> T) -> T {
switch self {
case nil:
return block()
default:
return self as! T
}
}
func getOrElse<T>(defaultValue: T) -> T {
switch self {
case nil:
return defaultValue
default:
return self as! T
}
}
}
// Usage
let string: String? = nil
print( "print default value:" )
print( string.getOrElse("default") )
print( "print default value from block:" )
print( string.getOrElse({
return "default in block"
}))
let string2: String? = "woah..."
print( "Don't print 'default', and print 'woah' twice:" )
print( string2.getOrElse("default") )
print( string2.getOrElse({
return "default in block"
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment