{"id":15634787,"url":"https://github.com/yonaskolb/codability","last_synced_at":"2025-07-20T10:35:42.063Z","repository":{"id":56906195,"uuid":"131011449","full_name":"yonaskolb/Codability","owner":"yonaskolb","description":"Useful helpers for working with Codable types in Swift","archived":false,"fork":false,"pushed_at":"2020-06-30T14:56:07.000Z","size":26,"stargazers_count":129,"open_issues_count":0,"forks_count":7,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-01-10T18:38:22.194Z","etag":null,"topics":["codable","decoding","encoding","helpers","json"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yonaskolb.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-04-25T13:34:55.000Z","updated_at":"2024-02-07T16:46:13.000Z","dependencies_parsed_at":"2022-08-21T03:20:48.170Z","dependency_job_id":null,"html_url":"https://github.com/yonaskolb/Codability","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yonaskolb%2FCodability","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yonaskolb%2FCodability/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yonaskolb%2FCodability/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yonaskolb%2FCodability/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yonaskolb","download_url":"https://codeload.github.com/yonaskolb/Codability/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234591888,"owners_count":18857012,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["codable","decoding","encoding","helpers","json"],"created_at":"2024-10-03T10:57:20.882Z","updated_at":"2025-01-19T02:23:19.340Z","avatar_url":"https://github.com/yonaskolb.png","language":"Swift","readme":"# Codability\n\n[![SPM](https://img.shields.io/badge/spm-compatible-brightgreen.svg?style=for-the-badge)](https://swift.org/package-manager)\n[![Git Version](https://img.shields.io/github/release/yonaskolb/Codability.svg?style=for-the-badge)](https://github.com/yonaskolb/Codability/releases)\n[![Build Status](https://img.shields.io/circleci/project/github/yonaskolb/Codability.svg?style=for-the-badge)](https://circleci.com/gh/yonaskolb/Codability)\n[![license](https://img.shields.io/github/license/yonaskolb/Codability.svg?style=for-the-badge)](https://github.com/yonaskolb/Codability/blob/master/LICENSE)\n\nUseful helpers for working with `Codable` types in Swift\n\n- [Invalid Element Strategy](#invalid-element-strategy)\n- [Any Codable](#any-codable)\n- [Raw CodingKey](#raw-codingkey)\n- [Generic Decoding Functions](#generic-decoding-functions)\n\n## Installing\n\n### Swift Package Manager\n\nAdd the following to your `Package.swift` dependencies:\n\n```swift\n.package(url: \"https://github.com/yonaskolb/Codability.git\", from: \"0.2.0\"),\n```\n\nAnd then import wherever needed: `import Codability`\n\n## Helpers\n\n### Invalid Element Strategy\nBy default Decodable will throw an error if a single element within an array or dictionary fails. `InvalidElementStrategy` is an enum that lets you control this behaviour. It has multiple cases:\n\n- `remove`: Removes the element from the collection\n- `fail`: Will fail the whole decoding. This is the default behaviour used by the decoders\n- `fallback(value)`: This lets you provide a typed value in a type safe way\n- `custom((EncodingError)-\u003e InvalidElementStrategy)`: Lets you provide dynamic behaviour depending on the specific error that was throw which lets you lookup exactly which keys were involved\n\nWhen decoding an array or dictionary use the `decodeArray` and `decodeDictionary` functions (there are also `IfPresent` variants as well).\n\nThe `InvalidElementStrategy` can either be passed into these functions, or a default can be set using `JSONDecoder().userInfo[.invalidElementStrategy]`, otherwise the default of `fail` will be used.\n\nGiven the following JSON:\n\n```json\n{\n    \"array\": [1, \"two\", 3],\n    \"dictionary\": {\n        \"one\": 1,\n        \"two\": \"two\",\n        \"three\": 3\n    }\n}\n```        \n```swift\nstruct Object: Decodable {\n\n    let array: [Int]\n    let dictionary: [String: Int]\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: RawCodingKey.self)\n        array = try container.decodeArray([Int].self, forKey: \"array\", invalidElementStrategy: .fallback(0))\n        dictionary = try container.decodeDictionary([String: Int].self, forKey: \"dictionary\", invalidElementStrategy: .remove)\n    }\n}\n```\n\n```swift\nlet decoder = JSONDecoder()\n\n// this will provide a default if none is passed into the decode functions\ndecoder.userInfo[.invalidElementStrategy] = InvalidElementStrategy\u003cAny\u003e.remove\n\nlet decodedObject = try decoder.decode(Object.self, from: json)\ndecodedObject.array == [1,0,3]\ndecodedObject.dictionary = [\"one\": 1, \"three\": 3]\n```\n\n### Any Codable\nThe downside of using Codable is that you can't encode and decode properties where the type is mixed or unknown, for example `[String: Any]`, `[Any]` or `Any`. \nThese are sometimes a neccessary evil in many apis, and `AnyCodable` makes supporting these types easy.\n\nThere are 2 few different way to use it:\n\n#### As a Codable property\nThe advantage of this is you can use the synthesized codable functions.\nThe downside though is that these values must be unwrapped using `AnyCodable.value`. You can add custom setters and getters on your objects to make accessing these easier though\n\n```swift\nstruct AnyContainer: Codable {\n    let dictionary: [String: AnyCodable]\n    let array: [AnyCodable]\n    let value: AnyCodable\n}\n```\n\n#### Custom decoding and encoding functions\n\nThis lets you keep your normal structures, but requires using the `decodeAny` or `encodeAny` functions. If you have to implement a custom `init(from:)` or `encode` function for other reasons, this is the way to go. Behind the scenes this uses `AnyCodable` to do the coding, and then does a cast to your expect type in the case of decoding. \n\n```swift\nstruct AnyContainer: Codable {\n    let dictionary: [String: Any]\n    let array: [Any]\n    let value: Any\n    \n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n\n        dictionary = try container.decodeAny(.dictionary)\n        array = try container.decodeAny([Any].self, forKey: .array)\n        value = try container.decodeAny(Any.self, forKey: .value)\n    }\n    \n    func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        try container.encodeAny(dictionary, forKey: .dictionary)\n        try container.encodeAny(array, forKey: .array)\n        try container.encodeAny(value, forKey: .value)\n    }\n    \n    enum CodingKeys: CodingKey {\n        case dictionary\n        case value\n        case array\n    }\n}\n```\n\n### Raw CodingKey\n`RawCodingKey` can be used to provide dynamic coding keys. It also remove the need to create the standard `CodingKey` enum when you are only using those values in once place.\n\n```swift\nstruct Object: Decodable {\n\n    let int: Int\n    let bool: Bool\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: RawCodingKey.self)\n        int = try container.decode(Int.self, forKey: \"int\")\n        bool = try container.decode(Bool.self, forKey: \"bool\")\n    }\n}\n```\n\n### Generic Decoding functions\nThe default decoding functions on `KeyedDecodingContainer` and `UnkeyedDecodingContainer` all require an explicity type to be passed in. `Codabilty` adds generic functions to remove the need for this, making your `init(from:)` much cleaner. The `key` parameter also becomes unnamed.\n\nAll the helper functions provided by `Codabality` such as the `decodeAny`, `decodeArray` or `decodeDictionary` functions also have these generic variants including `IfPresent`.\n\n```swift\nstruct Object: Decodable {\n\n    let int: Int?\n    let bool: Bool\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: RawCodingKey.self)\n        \n        // old\n        int = try container.decodeIfPresent(Int.self, forKey: \"int\")\n        bool = try container.decode(Bool.self, forKey: \"bool\")\n        \n        // new\n        int = try container.decodeIfPresent(\"int\")\n        bool = try container.decode(\"bool\")\n    }\n}\n\n```\n\n## Other Codability helpers\n[JohnSundell/Codextended](https://github.com/JohnSundell/Codextended)\n\n## Attributions\nThanks to @mattt and [Flight-School/AnyCodable](https://github.com/Flight-School/AnyCodable) for the basis of `AnyCodable` support. [License](https://github.com/Flight-School/AnyCodable/blob/master/LICENSE.md)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyonaskolb%2Fcodability","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyonaskolb%2Fcodability","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyonaskolb%2Fcodability/lists"}