Skip to content

Instantly share code, notes, and snippets.

@amfathi
Created May 16, 2020 16:19
Show Gist options
  • Save amfathi/855f255dec771d1bdf1d9820e88b054c to your computer and use it in GitHub Desktop.
Save amfathi/855f255dec771d1bdf1d9820e88b054c to your computer and use it in GitHub Desktop.
Handy extension for unwrap optionals
import Foundation
extension Optional where Wrapped == String {
/// Return true if the string value is not nil and not empty string
var exists: Bool {
switch self {
case .none:
return false
case .some(let string):
return !string.isEmpty
}
}
func unwrap(_ defaultValue: String = "") -> String {
if self.exists {
return self ?? defaultValue
} else {
return defaultValue
}
}
}
extension Optional where Wrapped == Bool {
func unwrap(_ defaultValue: Bool = false) -> Bool {
switch self {
case .none:
return defaultValue
case .some(let bool):
return bool
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment