Skip to content

Instantly share code, notes, and snippets.

@zef
Last active January 21, 2016 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zef/c6069ed4ed11e41661bf to your computer and use it in GitHub Desktop.
Save zef/c6069ed4ed11e41661bf to your computer and use it in GitHub Desktop.
Example of Swift enum with allValues array containing constructors for cases with associated values
protocol ValueEnumerable {
static var allValues: [Any] { get }
}
enum ColorScheme: ValueEnumerable {
typealias SchemeTuple = (name: String, background: UIColor, foreground: UIColor, border: UIColor)
case Light
case Dark
case custom(SchemeTuple)
var schemeData: SchemeTuple {
switch self {
case Light:
return ("Light", UIColor.whiteColor(), UIColor.blackColor(), UIColor.redColor())
case Dark:
return ("Dark", UIColor.blackColor(), UIColor.whiteColor(), UIColor.redColor())
case custom(let name, let background, let foreground, let border):
return (name, background, foreground, border)
}
}
// placeholder for what would be implemented in Swift
static var allValues: [Any] {
return [Light, Dark, custom]
}
static var userSchemeData: [SchemeTuple] {
// here you would pull data from however you want to persist the user themes
// but manually providing a sample of what it could look like
return [
("Some Custom Theme", UIColor.clearColor(), UIColor.clearColor(), UIColor.clearColor()),
("Another Custom Theme", UIColor.clearColor(), UIColor.clearColor(), UIColor.clearColor())
]
}
static var availableSchemes: [ColorScheme] {
return allValues.reduce([ColorScheme]()) { schemes, schemeCase in
var schemes = schemes
switch schemeCase {
case let instance as ColorScheme:
schemes.append(instance)
case let constructor as SchemeTuple -> ColorScheme:
for userScheme in userSchemeData {
schemes.append(constructor(userScheme))
}
default:
break
}
return schemes
}
}
}
let names = ColorScheme.availableSchemes.map { $0.schemeData.name }
names // ["Light", "Dark", "Some Custom Theme", "Another Custom Theme"]
let builtInValues = ColorScheme.allValues.flatMap { $0 as? ColorScheme }
builtInValues // ["Light", "Dark"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment