Skip to content

Instantly share code, notes, and snippets.

@krzemienski
Forked from Ericdowney/Optional Extensions.swift
Created September 6, 2018 10:10
Show Gist options
  • Save krzemienski/08c8da48b92a636f2d89f86e87d3d12c to your computer and use it in GitHub Desktop.
Save krzemienski/08c8da48b92a636f2d89f86e87d3d12c 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