Skip to content

Instantly share code, notes, and snippets.

@Ericdowney
Created August 24, 2018 20:46
Show Gist options
  • Save Ericdowney/59d33f53677bbe9ef11227716b1b03b3 to your computer and use it in GitHub Desktop.
Save Ericdowney/59d33f53677bbe9ef11227716b1b03b3 to your computer and use it in GitHub Desktop.
Swift gist for medium article explaining optional + extensions
extension Optional where Wrapped == String {
var valueOrEmpty: String {
guard let unwrapped = self else {
return ""
}
return unwrapped
}
}
let val: String? = "Hello"
//...
print(val.valueOrEmpty)
let booleanValue1 = Optional(true)! && Optional(false)!
//let booleanValue1 = Optional(nil)! && Optional(false)! // this generates an error
extension Optional where Wrapped == Bool {
var valueOrFalse: Bool {
guard let unwrapped = self else {
return false
}
return unwrapped
}
}
let optionalBool: Bool? = nil
let booleanValue2 = optionalBool.valueOrFalse && Optional(true).valueOrFalse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment