Skip to content

Instantly share code, notes, and snippets.

@zef zef/value-enumerable.swift
Last active Jan 21, 2016

What would you like to do?
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:
case let constructor as SchemeTuple -> ColorScheme:
for userScheme in userSchemeData {
return schemes
let names = { $ }
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
You can’t perform that action at this time.