Skip to content

Instantly share code, notes, and snippets.

@hujunfeng
Last active July 8, 2016 09:51
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 hujunfeng/f9595e1c00a953ee90f97940120d8e12 to your computer and use it in GitHub Desktop.
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.
/// 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