### Import KarrotCodableKit Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md Import the KarrotCodableKit framework in your Swift files to start using its functionalities. ```swift import KarrotCodableKit ``` -------------------------------- ### Example JSON for PolymorphicCodable Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md This JSON demonstrates dynamic content with different 'type' identifiers for various view items. ```json [ { "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" } ] ``` -------------------------------- ### Package Management Commands Source: https://github.com/daangn/karrotcodablekit/blob/main/CLAUDE.md Manages Swift package dependencies and build artifacts. Use 'resolve' to fetch dependencies, 'update' to get the latest versions, 'clean' to remove build artifacts, and 'reset' to clear the cache. ```bash swift package resolve ``` ```bash swift package update ``` ```bash swift package clean ``` ```bash swift package reset ``` -------------------------------- ### Set Default Value with Custom Strategy Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Implement custom default values for Codable properties using @DefaultCodable and a conforming strategy. This example shows setting a default CacheInterval. ```Swift struct RefreshDaily: DefaultCodableStrategy { static var defaultValue: CacheInterval { return CacheInterval.daily } } struct Cache: Codable { @DefaultCodable var refreshInterval: CacheInterval } let json = #"{ "refreshInterval": null }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Cache.self, from: json) print(result) // Cache(refreshInterval: .daily) ``` -------------------------------- ### Build All Targets Source: https://github.com/daangn/karrotcodablekit/blob/main/CLAUDE.md Builds all targets in the Swift package. Use '-c release' for a release build. ```bash swift build ``` ```bash swift build -c release ``` -------------------------------- ### Run All Tests Source: https://github.com/daangn/karrotcodablekit/blob/main/CLAUDE.md Executes all tests within the Swift package. Specify '-c debug' or '-c release' for configuration-specific tests. ```bash swift test ``` ```bash swift test -c debug ``` ```bash swift test -c release ``` -------------------------------- ### Add KarrotCodableKit to Package.swift Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md Add the KarrotCodableKit framework to your project's Package.swift file using Swift Package Manager. ```swift dependencies: [ .package(url: "https://github.com/daangn/KarrotCodableKit.git", from: "1.1.0") ] ``` -------------------------------- ### Decoding with AnyDecodable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/AnyCodable/README.md Shows how to decode a JSON string into a dictionary of AnyDecodable values. This is useful for parsing JSON where value types might vary. ```swift let json = """ { "boolean": true, "integer": 1, "double": 3.141592653589793, "string": "string", "array": [1, 2, 3], "nested": { "a": "alpha", "b": "bravo", "c": "charlie" }, "null": null }""" \ .data(using: .utf8)! let decoder = JSONDecoder() let dictionary = try! decoder.decode([String: AnyDecodable].self, from: json) ``` -------------------------------- ### Encoding with AnyEncodable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/AnyCodable/README.md Demonstrates how to use AnyEncodable to wrap various Swift types for JSON encoding. This is useful for creating dictionaries with heterogeneous value types. ```swift import AnyCodable let dictionary: [String: AnyEncodable] = [ "boolean": true, "integer": 1, "double": 3.141592653589793, "string": "string", "array": [1, 2, 3], "nested": [ "a": "alpha", "b": "bravo", "c": "charlie" ], "null": nil ] let encoder = JSONEncoder() let json = try! encoder.encode(dictionary) ``` -------------------------------- ### Run Specific Tests Source: https://github.com/daangn/karrotcodablekit/blob/main/CLAUDE.md Filters tests to run specific classes, methods, or patterns. Use quotes for patterns with spaces. ```bash swift test --filter TestClassName ``` ```bash swift test --filter TestClassName.testMethodName ``` ```bash swift test --filter UnnestedPolymorphic ``` ```bash swift test --filter "UnnestedPolymorphicCodableTests" ``` -------------------------------- ### Basic CustomCodable Usage Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md Use the @CustomCodable macro to automatically implement the Codable protocol and generate CodingKeys for a struct. Use @CodableKey to customize specific property names. ```swift @CustomCodable struct Person { let name: String let age: Int @CodableKey(name: "userProfileUrl") let userProfileURL: String } ``` -------------------------------- ### Snake Case Conversion with CustomCodable Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md Configure @CustomCodable with codingKeyStyle: .snakeCase to automatically convert property names to snake_case for coding keys. ```swift @CustomCodable(codingKeyStyle: .snakeCase) struct User { let firstName: String let lastLogin: Date } ``` -------------------------------- ### Default Array to Empty Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Employ @DefaultEmptyArray to provide an empty array instead of nil when the decoded array value is null. ```Swift struct Response: Codable { @DefaultEmptyArray var favorites: [Favorite] } let json = #"{ "favorites": null }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // Response(favorites: []) ``` -------------------------------- ### PolymorphicCodable Swift Implementation Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md Defines a structure with polymorphic properties using property wrappers and a protocol for dynamic type resolution. ```swift @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 } ``` -------------------------------- ### Expanded Basic CustomCodable Usage Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md This shows the expanded code generated by the @CustomCodable macro for the Person struct, including the generated CodingKeys enum and Codable conformance. ```swift 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 { } ``` -------------------------------- ### Lossless Value Decoding for Codable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Employ @LosslessValue to decode values into the expected type, even if the API provides them in a different, but convertible, format (e.g., Int as String, String as Bool). ```Swift struct Response: Codable { @LosslessValue var sku: String @LosslessValue var isAvailable: Bool } let json = #"{ "sku": 12345, "isAvailable": "true" }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // Response(sku: "12355", isAvailable: true) ``` -------------------------------- ### Default Dictionary to Empty Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Use @DefaultEmptyDictionary to return an empty dictionary when the decoded dictionary value is null. ```Swift struct Response: Codable { @DefaultEmptyDictionary var settings: [String: String] } let json = #"{ "settings": null }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // Response(settings: [:]) ``` -------------------------------- ### Mixed Date Strategies for Codable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Combine different @DateValue strategies within a single Codable struct to handle multiple date formats from a JSON response. ```Swift struct Response: Codable { @DateValue var updatedAt: Date @DateValue var birthday: Date } let json = #"{ "updatedAt": "2019-10-19T16:14:32-05:00", "birthday": "1984-01-22" }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) // This produces two valid `Date` values, `updatedAt` representing October 19, 2019 and `birthday` January 22nd, 1984. ``` -------------------------------- ### Default Empty Dictionary for Codable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Use @DefaultEmptyDictionary to ensure a dictionary property is decoded as an empty dictionary when the JSON value is null. ```Swift struct Response: Codable { @DefaultEmptyDictionary var scores: [String: Int] } let json = #"{ "scores": null }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // Response(values: [:]) ``` -------------------------------- ### Year-Month-Day Date Decoding for Codable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Employ @DateValue to decode dates in 'y-MM-dd' format into Date objects. Encoding converts the Date back to the 'y-MM-dd' string format. ```Swift struct Response: Codable { @DateValue var date: Date } let json = #"{ "date": "2001-01-01" }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) // This produces a valid `Date` representing January 1st, 2001. ``` -------------------------------- ### Expanded Snake Case Conversion Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md This illustrates the code generated by @CustomCodable when using the .snakeCase codingKeyStyle, showing the mapping from camelCase properties to snake_case coding keys. ```swift struct User { let firstName: String let lastLogin: Date private enum CodingKeys: String, CodingKey { case firstName = "first_name" case lastLogin = "last_login" } } extension User: Codable { } ``` -------------------------------- ### Default Boolean to False Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Use @DefaultFalse to ensure a Bool property defaults to false if the decoded value is null or an unexpected type. ```Swift struct UserPrivilege: Codable { @DefaultFalse var isAdmin: Bool } let json = #"{ "isAdmin": null }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // UserPrivilege(isAdmin: false) ``` -------------------------------- ### ISO8601 Date Decoding for Codable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Use @DateValue to decode ISO8601 formatted date strings into Date objects. Encoding converts the Date back to its ISO8601 string representation. ```Swift struct Response: Codable { @DateValue var date: Date } let json = #"{ "date": "1996-12-19T16:39:57-08:00" }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) // This produces a valid `Date` representing 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time). ``` -------------------------------- ### Decode Dictionary with Lossy Values Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Utilize @LossyDictionary to filter out dictionary entries where the value is null or cannot be decoded. ```Swift struct Response: Codable { @LossyDictionary var values: [String: String] } let json = #"{ "values": {"a": "A", "b": "B", "c": null } }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // ["a": "A", "b": "B"] ``` -------------------------------- ### Decode Dictionary with Failable Entities Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Use @LossyDictionary to exclude dictionary entries where the value is an entity that fails to decode. ```Swift struct Failable: Codable { let value: String } struct Response: Codable { @LossyDictionary var values: [String: Failable] } let json = #"{ "values": {"a": {"value": "A"}, "b": {"value": 2}} }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // ["a": "A"] ``` -------------------------------- ### RFC3339 Date Decoding for Codable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Utilize @DateValue for decoding RFC 3339 date strings into Date objects. Encoding converts the Date back to its RFC3339 string representation. ```Swift struct Response: Codable { @DateValue var date: Date } let json = #"{ "date": "1996-12-19T16:39:57-08:00" }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) // This produces a valid `Date` representing 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time). ``` -------------------------------- ### Timestamp Date Decoding for Codable Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Use @DateValue to decode Unix epoch timestamps (Doubles) into Date objects. Encoding converts the Date back to its TimeInterval representation. ```Swift struct Response: Codable { @DateValue var date: Date } let json = #"{ "date": 978307200.0 }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) // This produces a valid `Date` representing January 1st, 2001. ``` -------------------------------- ### Decode Array with Lossy Values Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Use @LossyArray to automatically filter out null or undecodable elements from an array during decoding. ```Swift struct Response: Codable { @LossyArray var values: [Int] } let json = #"{ "values": [1, 2, null, 4, 5, null] }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // [1, 2, 4, 5] ``` -------------------------------- ### Decode Array with Failable Entities Source: https://github.com/daangn/karrotcodablekit/blob/main/Docs/BetterCodable/README.md Employ @LossyArray to exclude array elements that fail to decode, such as those with incorrect data types. ```Swift struct Failable: Codable { let value: String } struct Response: Codable { @LossyArray var values: [Failable] } let json = #"{ "values": [{"value": 4}, {"value": "fish"}] }"#.data(using: .utf8)! let result = try JSONDecoder().decode(Response.self, from: json) print(result) // [Failable(value: "fish")] ``` -------------------------------- ### PolymorphicEnumCodable Swift Implementation Source: https://github.com/daangn/karrotcodablekit/blob/main/README.md Defines a Swift enum for handling polymorphic types, mapping JSON identifiers to enum cases with associated types. ```swift @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 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.