Last active
August 2, 2017 17:39
-
-
Save tayloraswift/ba42b620f80ee94fbb0d0841056aac97 to your computer and use it in GitHub Desktop.
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
// 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