Skip to content

Instantly share code, notes, and snippets.

@NinoScript
Last active January 26, 2017 17:11
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 NinoScript/a0b7e88ad795daa0ba28a0f9cdf28d24 to your computer and use it in GitHub Desktop.
Save NinoScript/a0b7e88ad795daa0ba28a0f9cdf28d24 to your computer and use it in GitHub Desktop.
Playing around with the concept of "emptiable" values
//: Playground - noun: a place where people can play
import Cocoa
protocol Emptiable {
static var emptyValue: Self { get }
}
extension Emptiable where Self: Equatable {
var nonEmptyValue: Self? {
return self == Self.emptyValue ? nil : self
}
}
extension Optional where Wrapped: Emptiable {
var valueOrEmpty: Wrapped {
return self ?? Wrapped.emptyValue
}
}
extension Optional where Wrapped: Emptiable & Equatable {
func nonEmptyValue(orDefault defaultValue: Wrapped) -> Wrapped {
return self?.nonEmptyValue ?? defaultValue
}
}
extension String: Emptiable {
static let emptyValue = ""
}
var str1: String? = "Hello, playground"
var str2: String? = ""
var str3: String? = nil
str1?.nonEmptyValue // "Hello, playground"
str2?.nonEmptyValue // nil
str3?.nonEmptyValue // nil
let defaultString = "default"
str1.nonEmptyValue(orDefault: defaultString) // "Hello, playground"
str2.nonEmptyValue(orDefault: defaultString) // "default"
str3.nonEmptyValue(orDefault: defaultString) // "default"
str1.valueOrEmpty // "Hello, playground"
str2.valueOrEmpty // ""
str3.valueOrEmpty // ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment