How can I use Swift's Codable to encode into a dictionary?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Swift's Codable protocol is designed for encoding to and decoding from external formats like JSON. There is no built-in DictionaryEncoder, but you can convert a Codable object to a [String: Any] dictionary by encoding it to JSON data first, then deserializing that data with JSONSerialization. For a cleaner approach, you can write a custom DictionaryEncoder that avoids the intermediate JSON step.
Method 1: JSON Round-Trip (Simple)
Encode to JSON, then deserialize to a dictionary:
This works for any Codable type. The downside is two serialization steps (encode to JSON bytes, then parse those bytes back to objects).
Method 2: Extension on Encodable (Reusable)
Method 3: Custom DictionaryEncoder
For a direct conversion without JSON intermediary:
Nested Objects
Custom Coding Keys
The dictionary keys follow the CodingKeys mapping, producing snake_case keys.
Date Encoding Strategies
Using with Firestore / API Payloads
Dictionary Back to Codable
Common Pitfalls
Dateencoding defaults toDouble: Without settingdateEncodingStrategy,JSONEncoderencodesDateas aTimeInterval(seconds since 1970). Set.iso8601or.formattedfor readable dates in your dictionary.Anytype is notCodable: You cannot encode[String: Any]withJSONEncoderbecauseAnydoes not conform toCodable. UseJSONSerializationfor untyped dictionaries.- Enums without raw values: Enums with associated values need custom
Codableconformance. Without it, encoding fails at runtime. - Optional fields are omitted: By default,
JSONEncoderomitsniloptional properties. The resulting dictionary will not have keys fornilvalues. If you need explicitnull, use custom encoding. Float/Doubleprecision: JSON serialization may introduce floating-point precision artifacts.3.14might become3.1400000000000001in the dictionary. UseDecimalfor exact values.
Summary
- Encode to JSON with
JSONEncoder, then parse to[String: Any]withJSONSerialization - Create an
Encodableextension withasDictionary()for reusable conversion - Custom
CodingKeyscontrol the dictionary key names (e.g., camelCase to snake_case) - Set
dateEncodingStrategyonJSONEncoderto control how dates appear in the dictionary - To go from dictionary back to
Codable, serialize withJSONSerializationthen decode withJSONDecoder
Related reading
- How can I verify if one list is a subset of another?
- How can I view the enqueued tasks in RabbitMQ?
- How can queues be made private/secure in RabbitMQ in a multitenancy system?
- How can stdmake_heap be implemented while making at most 3N comparisons?
- How can I use Tensorflow with react-native?
- How can I use Tensorflow with react-native?
- How can stdvector access elements with huge gaps between them?
- How can we find the starting node of a loop in link list?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.