Skip to content

Instantly share code, notes, and snippets.

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