Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.