This document details the various coding strategies implemented in MetaCodable and how to extend them.
graph LR
A[Source Key] --> B[Transformation]
B --> C[Target Key]
B --> D[snake_case]
B --> E[camelCase]
B --> F[PascalCase]
B --> G[SCREAMING_SNAKE_CASE]
Key transformations are handled through:
CodingKeys(_:)attribute for global key styleCodedAt(_:)for individual property key mapping- Built-in support for various case styles
MetaCodable provides several strategies for handling nested data structures:
- Flattened Models
@Codable
struct Coordinate {
var latitude: Double
var longitude: Double
@CodedIn("additionalInfo")
var elevation: Double
}This automatically handles JSON like:
{
"latitude": 0,
"longitude": 0,
"additionalInfo": {
"elevation": 0
}
}- Path-Based Access
- Use
CodedAt(_:)for direct path access - Support for multiple path components
- Automatic container management
The HelperCoder protocol is the foundation for custom coding strategies:
protocol HelperCoder {
associatedtype Coded
func decode(from decoder: Decoder) throws -> Coded
func encode(_ value: Coded, to encoder: Encoder) throws
}Built-in helper coders include:
- ValueCoder: Direct value coding
- SequenceCoder: Collection handling
- DateCoder: Date format handling
- Base64Coder: Binary data encoding
- Implement the
HelperCoderprotocol - Handle encoding and decoding logic
- Use with
@CodedByattribute
Example:
struct CustomDateCoder: HelperCoder {
let formatter: DateFormatter
func decode(from decoder: Decoder) throws -> Date {
let string = try String(from: decoder)
guard let date = formatter.date(from: string) else {
throw DecodingError.dataCorruptedError(
in: decoder as! any SingleValueDecodingContainer,
debugDescription: "Invalid date format"
)
}
return date
}
func encode(_ value: Date, to encoder: Encoder) throws {
try formatter.string(from: value).encode(to: encoder)
}
}The MetaProtocolCodable build tool plugin supports:
-
Dynamic Protocol Implementation
- Automatic conformance generation
- Type-safe protocol handling
- Cross-module support
-
Build Process Integration
- Source code scanning
- Implementation generation
- Build-time validation
-
Key Naming
- Use consistent naming conventions
- Leverage built-in transformations
- Document custom key mappings
-
Error Handling
- Provide meaningful default values
- Use appropriate error strategies
- Handle missing values gracefully
-
Performance
- Use appropriate container types
- Minimize nesting depth
- Leverage built-in optimizations