Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:16
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 JadenGeller/a4606c8b8f53a43ce765 to your computer and use it in GitHub Desktop.
Save JadenGeller/a4606c8b8f53a43ce765 to your computer and use it in GitHub Desktop.
Swift Unwrap Function
/*
* Returns the default value whenever the primary value is nil
* Otherwise returns the primary value
*/
func unwrap<T>(primaryValue: T?, defaultValue: T) -> T {
if let value = primaryValue { return value }
else { return defaultValue }
}
// Examples
// Fancy swift-style optional integers
let x: Int? = 2
let y: Int? = nil
// C-style non-nilable integers
let oldX = unwrap(x, 0) // -> 2
let oldY = unwrap(y, 0) // -> 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment