Created
September 4, 2016 21:32
-
-
Save amlcurran/0e4806c355ca235d3aa2b47280c1da16 to your computer and use it in GitHub Desktop.
Some fluent wrappers around the nil-coalescing operator and optionals in Swift
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
extension Optional { | |
func or(_ backup: Wrapped) -> Wrapped { | |
if let wrapped = self { | |
return wrapped | |
} | |
return backup | |
} | |
} | |
extension Optional where Wrapped: ExpressibleByArrayLiteral { | |
func orEmpty() -> Wrapped { | |
let emptyArray: Wrapped = [] | |
return or(emptyArray) | |
} | |
} | |
let string: String? = nil | |
string.or("alternative").utf8.count // returns 11 | |
let array: [String]? = nil | |
array.orEmpty().count // returns 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment