Created
September 28, 2016 17:52
-
-
Save AmitaiB/e3f14b119b4953b451d44de582436096 to your computer and use it in GitHub Desktop.
Provides failable initializers for X-Literals, e.g., `String(suspectedString) // returns a String optional`, just like `String(5) // returns a String, "5"`
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
/* | |
Instead of, say: | |
if let definitelyAString = perhapsAString as? String { // yadda... } | |
We now have: | |
String(perhapsAString) // returns a String? (an optional) | |
*/ | |
protocol OptionalLiteralType { | |
init?(_ input: Any?) | |
} | |
// The magic, brought to you by Default Protocol Implementations | |
// cf. The Swift Programming Language p.533 | |
extension OptionalLiteralType { | |
init?(_ input: Any?) { | |
guard let typedValue = input as? Self else { return nil } | |
self = typedValue | |
} | |
} | |
extension StringLiteralType: OptionalLiteralType {} | |
extension FloatLiteralType: OptionalLiteralType {} | |
extension IntegerLiteralType: OptionalLiteralType {} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Provides failable initializers for X-Literals, e.g.,
String(suspectedString) // returns a String optional
,just like
String(5) // returns a String, "5"