Skip to content

Instantly share code, notes, and snippets.

@tayloraswift
Last active August 2, 2017 17:39
Show Gist options
  • Save tayloraswift/ba42b620f80ee94fbb0d0841056aac97 to your computer and use it in GitHub Desktop.
Save tayloraswift/ba42b620f80ee94fbb0d0841056aac97 to your computer and use it in GitHub Desktop.
// whether or not the string conversions live in the main definition depends on whether
// or not the strings are used for debugging/UI purposes, or have an actual internal role
// in the program
enum CasualAnswer
{
case noWay,
yeahSure
// Supported conversions from: Bool
init(_ value:Bool)
{
self = value ? .yeahSure : .noWay
}
}
extension CasualAnswer:LosslessStringConvertible // String Compatibility
{
init?(_ description:String)
{
switch description
{
case "no way":
self = .noWay
case "yeah sure":
self = .yeahSure
default:
return nil
}
}
var description:String
{
switch self
{
case .noWay:
return "no way"
case .yeahSure:
return "yeah sure"
}
}
}
// we are modifying a stdlib type to support a conversion to our custom type.
// this is conceptually different from an opposite conversion from our
// custom type to a stdlib type.
// public // why are you making a *public* extension of a stdlib type? this is a *bad* idea
extension Bool
{
init(_ value:CasualAnswer)
{
switch value
{
case .noWay:
self = false
case .yeahSure:
self = true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment