Skip to content

Instantly share code, notes, and snippets.

@dterekhov
Last active October 24, 2025 06:48
Show Gist options
  • Select an option

  • Save dterekhov/588ba32e6a7c151668e9bbf20f3b7c38 to your computer and use it in GitHub Desktop.

Select an option

Save dterekhov/588ba32e6a7c151668e9bbf20f3b7c38 to your computer and use it in GitHub Desktop.
Enum Codable synthesis #persistence #swift-api
import Foundation
enum Command: Codable {
case load(key: String)
case store(key: String, value: Int)
}
@main
struct Demo {
static func main() throws {
let command: Command = .store(key: "volume", value: 10)
// Encode
let data = try JSONEncoder().encode(command)
print(String(data: data, encoding: .utf8)!)
// Example output: {"store":{"key":"volume","value":10}}
// Decode
let decoded = try JSONDecoder().decode(Command.self, from: data)
print(decoded) // prints store(key: "volume", value: 10)
}
}
@dterekhov
Copy link
Author

54B407C0-B686-4A2F-AB35-6F46E958173A

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment