Skip to content

Instantly share code, notes, and snippets.

@AmitaiB
Created September 28, 2016 17:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmitaiB/e3f14b119b4953b451d44de582436096 to your computer and use it in GitHub Desktop.
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"`
/*
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 {}
@AmitaiB
Copy link
Author

AmitaiB commented Sep 28, 2016

Provides failable initializers for X-Literals, e.g.,

String(suspectedString) // returns a String optional,

just like

String(5) // returns a String, "5"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment