| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
KarrotCodableKit is a library that extends Swift's Codable protocol to provide more powerful and flexible data encoding and decoding capabilities. It helps handle complex JSON structures and enables type-safe transformations for various data formats.
This library includes the following key features:
KarrotCodableKit simplifies the conversion of models from various data sources such as network responses, local storage, and enables developers to reduce development time and improve code quality.
See the documentation for more details or Ask DeepWiki.
You can install this framework using Swift Package Manager:
Or add it to your Package.swift file:
dependencies: [
.package(url: "https://github.com/daangn/KarrotCodableKit.git", from: "1.1.0")
]Then import the framework in the files where you want to use it:
import KarrotCodableKitNow you're ready to use the KarrotCodableKit framework.
CustomCodable is a macro that simplifies implementing Swift's Codable protocol. This feature automatically generates the CodingKeys enum and adopts the Codable protocol.
@CustomCodable
struct Person {
let name: String
let age: Int
@CodableKey(name: "userProfileUrl")
let userProfileURL: String
}The code above expands to:
struct Person {
let name: String
let age: Int
let userProfileURL: String
private enum CodingKeys: String, CodingKey {
case name
case age
case userProfileURL = "userProfileUrl"
}
}
extension Person: Codable {
}Setting codingKeyStyle to .snakeCase converts property names to snake_case for coding keys:
@CustomCodable(codingKeyStyle: .snakeCase)
struct User {
let firstName: String
let lastLogin: Date
}The code above expands to:
struct User {
let firstName: String
let lastLogin: Date
private enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastLogin = "last_login"
}
}
extension User: Codable {
}PolymorphicCodable provides functionality to easily decode polymorphic types from JSON. This functionality provides Swift implementation for the OpenAPI Specification's oneOf pattern, allowing type-safe handling of multiple possible schemas. It includes several interfaces like PolymorphicIdentifiable, PolymorphicCodableStrategy, and property wrappers like PolymorphicValue and PolymorphicArrayValue.
Parameters:
The following example demonstrates how to decode dynamic JSON content where the type of object is determined at runtime:
[
{
"type": "IMAGE_VIEW_ITEM",
"id": "008c377d-9ea0-4fae-9ae3-e2da27be4be7",
"image_url": "https://example.com/images/banner.jpg"
},
{
"type": "TEXT_VIEW_ITEM",
"id": "1fdb2bee-394e-4d61-b3b8-73f8b668d47f",
"title": "Welcome Message",
"description": "Welcome to Karrot"
},
{
"type": "IMAGE_VIEW_ITEM",
"id": "acf5644d-dd46-46f4-a497-e0ea3eef23d1",
"title": "Karrot",
"banner_image_url": "https://example.com/images/banner2.jpg"
}
]PolymorphicCodable enables you to decode dynamic JSON structures where the concrete type is determined by a type identifier field. The library handles this dynamic type resolution automatically during decoding:
@CustomCodable
struct APIResponse {
@ViewItem.Polymorphic
var viewItem: ViewItem
@ViewItem.OptionalPolymorphic
var optionalViewItem: ViewItem?
@ViewItem.PolymorphicArray
var viewItems: [ViewItem]
@ViewItem.PolymorphicLossyArray
var lossyViewItems: [ViewItem]
@ViewItem.OptionalPolymorphicLossyArray
var optionalLossyViewItems: [ViewItem]?
}
// MARK: - protocol
@PolymorphicCodableStrategyProviding(
identifierCodingKey: "type",
matchingTypes: [
ImageViewItem.self,
TextViewItem.self,
],
fallbackType: UndefinedViewItem.self
)
protocol ViewItem: Codable {
var id: String { get }
}
// MARK: - items
@PolymorphicCodable(
identifier: "IMAGE_VIEW_ITEM",
codingKeyStyle: .snakeCase
)
struct ImageViewItem: ViewItem {
let id: String
let imageURL: URL
}
@PolymorphicCodable(identifier: "TEXT_VIEW_ITEM")
struct TextViewItem: ViewItem {
let id: String
let title: String
let description: String
}
@PolymorphicCodable(identifier: "UNDEFINED_VIEW_ITEM")
struct UndefinedViewItem: ViewItem {
let id: String
}The generated strategy conforms to PolymorphicMatchingTypesProviding, which exposes the family as values. decode(from:) reads the very same properties, so the exposed list cannot drift away from what decoding resolves.
ViewItemCodableStrategy.matchingTypes // [ImageViewItem.self, TextViewItem.self]
ViewItemCodableStrategy.fallbackType // UndefinedViewItem.selfConstrain a generic parameter to the protocol when a caller must be handed the production strategy rather than a list assembled by hand — for example, to check that every declared type has a registered handler:
func assertEveryTypeHasHandler<Strategy: PolymorphicMatchingTypesProviding>(
declaredIn _: Strategy.Type,
registeredIdentifiers: Set<String>,
) {
let declared = Set(Strategy.matchingTypes.map { $0.polymorphicIdentifier })
#expect(declared.subtracting(registeredIdentifiers).isEmpty)
}
assertEveryTypeHasHandler(
declaredIn: ViewItemCodableStrategy.self,
registeredIdentifiers: Set(handlers.keys),
)PolymorphicMatchingTypesProviding refines PolymorphicCodableStrategy rather than adding requirements to it, so hand-written strategies keep working unchanged and adopt it only when they need to be enumerated.
PolymorphicEnumCodable provides a convenient way to handle polymorphic types directly in Swift enums. Unlike PolymorphicCodable which works with protocol-conforming types, this macro allows you to define an enum where each case contains an associated value of a different type, and enables seamless JSON encoding and decoding.
When decoding, the macro uses the value of the specified identifierCodingKey to determine which enum case to use. It then uses the associated type's polymorphicIdentifier to match and decode the data.
Parameters:
Each enum case must have exactly one associated value of a type that adopts the PolymorphicCodableType protocol.
@PolymorphicEnumCodable(
identifierCodingKey: "type",
fallbackCaseName: "undefined"
)
enum ViewItem {
case image(ImageViewItem)
case text(TextViewItem)
case undefined(UndefinedViewItem)
}
@PolymorphicCodable(
identifier: "IMAGE_VIEW_ITEM",
codingKeyStyle: .snakeCase
)
struct ImageViewItem {
let id: String
let imageURL: URL
}
@PolymorphicCodable(identifier: "TEXT_VIEW_ITEM")
struct TextViewItem {
let id: String
let title: String
let description: String
}
@PolymorphicCodable(identifier: "UNDEFINED_VIEW_ITEM")
struct UndefinedViewItem: ViewItem {
let id: String
}Type-erased wrappers for Encodable, Decodable, and Codable values.
See details README.md
Level up your Codable structs through property wrappers. The goal of these property wrappers is to avoid implementing a custom init(from decoder: Decoder) throws and suffer through boilerplate.
See details README.md
We welcome all contributions to this project! Feel free to submit pull requests to enhance the functionality of this project.
This project is licensed under the MIT. See LICENSE for details.
| Back | FazBrowse Home | New Git URL |