Last active
August 29, 2015 14:16
-
-
Save JadenGeller/a4606c8b8f53a43ce765 to your computer and use it in GitHub Desktop.
Swift Unwrap Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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