Created
August 24, 2018 20:46
-
-
Save Ericdowney/59d33f53677bbe9ef11227716b1b03b3 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