Last active
July 8, 2016 09:51
-
-
Save hujunfeng/f9595e1c00a953ee90f97940120d8e12 to your computer and use it in GitHub Desktop.
A `safeValue` method for Optional type. It returns an empty value if the wrapped type of the Optional type has one, for example String and Array.
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
/// A type that supports an "empty value" | |
protocol EmptyValuable { | |
/// Returns the empty value of `Self` | |
static var emptyValue: Self { get } | |
} | |
extension String: EmptyValuable { | |
static var emptyValue: String { | |
return "" | |
} | |
} | |
extension Array: EmptyValuable { | |
static var emptyValue: [Element] { | |
return [] | |
} | |
} | |
extension Optional where Wrapped: EmptyValuable { | |
/// If `self` is non-`nil`, returns the unwrapped value. Otherwise, returns an empty value of the `Wrapped` type | |
var safeValue: Wrapped { | |
return self != nil ? self! : Wrapped.emptyValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment