Skip to content

Instantly share code, notes, and snippets.

@polac24
Last active March 13, 2018 15:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polac24/64a4d5e6cef873428df58df8bb1f532e to your computer and use it in GitHub Desktop.
Save polac24/64a4d5e6cef873428df58df8bb1f532e to your computer and use it in GitHub Desktop.
// Custom RawRepresentable type for BestEnum
struct BestEnumRaw: ExpressibleByStringLiteral{
let rawString:String?
init(){
rawString = nil
}
init(stringLiteral value: String){
rawString = value
}
init(extendedGraphemeClusterLiteral value: String){
rawString = value
}
init(unicodeScalarLiteral value: String){
rawString = value
}
}
extension BestEnumRaw: Equatable{
// Before actual comparison, fill static `all` set with String value
// that corresponds to the enum case
static func ==(lhs: BestEnumRaw, rhs: BestEnumRaw) -> Bool {
if let lhsRaw = lhs.rawString { BestEnum.all.insert(lhsRaw)}
if let rhsRaw = rhs.rawString { BestEnum.all.insert(rhsRaw)}
return lhs.rawString == rhs.rawString
}
}
enum BestEnum:BestEnumRaw{
// bucket for all representable Strings
static var all:Set<String> = []
case myCase = "my_case"
case otherCase = "otherCase"
}
// ensuring that all static var fills with raw values
BestEnum(rawValue: BestEnumRaw())
// allCases: Array<BestEnum>
let allCases = BestEnum.all.map({BestEnumRaw(stringLiteral: $0)}).flatMap(BestEnum.init)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment