Created
May 16, 2020 16:19
-
-
Save amfathi/855f255dec771d1bdf1d9820e88b054c to your computer and use it in GitHub Desktop.
Handy extension for unwrap optionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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