Skip to content

Instantly share code, notes, and snippets.

@xxKRASHxx
Created February 27, 2019 22:29
Show Gist options
  • Save xxKRASHxx/9af2a1d82b18c04e63ef254d2508b92e to your computer and use it in GitHub Desktop.
Save xxKRASHxx/9af2a1d82b18c04e63ef254d2508b92e to your computer and use it in GitHub Desktop.
import Foundation
<%
func camelCased(_ string: String) -> String {
return "\(String(string.first!).lowercased())\(String(string.dropFirst()))".replacingOccurrences(of: ".", with: "")
}
func allEvents() -> [Type] {
return types.all.filter { type in
(type is Struct || type is Enum) && (type.implements["AppEvent"] != nil)
}
}
-%>
enum AnyEvent: Codable {
<%_ for type in allEvents() { -%>
case <%= camelCased(type.name) %>(<%= type.name %>)
<%_ } -%>
init(_ event: AppEvent) {
switch event {
<%_ for type in allEvents() { -%>
case let event as <%= type.name %>: self = .<%= camelCased(type.name) %>(event)
<%_ } -%>
default: fatalError("Unexpected event")
}
}
var event: AppEvent {
switch self {
<%_ for type in allEvents() { -%>
case let .<%= camelCased(type.name) %>(event): return event
<%_ } -%>
}
}
enum Keys: CodingKey {
case type, event
}
enum EventType: String, Codable {
<%_ for type in allEvents() { -%>
case <%= camelCased(type.name) %>
<%_ } -%>
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
let type = try container.decode(EventType.self, forKey: .type)
switch type {
<%_ for type in allEvents() { -%>
case .<%= camelCased(type.name) %>: self = .<%= camelCased(type.name) %>(try container.decode(<%= type.name %>.self, forKey: .event))
<%_ } -%>
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Keys.self)
switch self {
<%_ for type in allEvents() { -%>
case .<%= camelCased(type.name) %>(let event):
try container.encode(EventType.<%= camelCased(type.name) %>, forKey: .type)
try container.encode(event, forKey: .event)
<%_ } -%>
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment