CodingKeyRepresentable
The CodingKeyRepresentable
protocol provides the flexibility to covert between a CodingKey
type and a personalized type. This protocol enables the use of dictionaries that are not a String
or Int
(non-standard keys) to be encoded using organized ‘keyed’ containers instead of ‘unkeyed’ containers.
Syntax
protocol CodingKeyRepresentable
Note: CodingKeyRepresentable allows for the creation of methods to convert data into a string format that function as a key. This is particularly useful when implementing custom structs as keys.
Example
In the following example, an enum named NewSettings
is declared, and it contains two options: name
and instagram
. This list can be used to organize data (e.g. settings for a profile). Then, a dictionary named newDict
is created, and it uses NewSettings
as keys to be associated with new string values.
Then a tool called JSONEncoder
is used to convert this dictionary into a special format called JSON. The JSON data is turned into readable text and the output is shown in an object format.
enum NewSettings: String, Codable, CodingKeyRepresentable {case namecase instagram}let newDict: [NewSettings: String] = [.name: "Jay", .instagram: "@CelticsfanJay"]let newData = try! JSONEncoder().encode(newDict)print(String(decoding: newData, as: UTF8.self))
This code returns the following output:
Output: {"instagram":"@CelticsfanJay","name":"Jay”}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours