-
-
Save krzemienski/08c8da48b92a636f2d89f86e87d3d12c to your computer and use it in GitHub Desktop.
Swift gist for medium article explaining optional + extensions
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
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