0
0
Swiftprogramming~5 mins

Codable protocol for encoding/decoding in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the Codable protocol in Swift?
The Codable protocol is a combination of Encodable and Decodable. It allows Swift types to be easily converted to and from external representations like JSON or Property Lists.
Click to reveal answer
beginner
How do you make a Swift struct conform to Codable?
You add Codable to the struct's declaration. For example: <br>
struct User: Codable {<br>  var name: String<br>  var age: Int<br>}
Click to reveal answer
intermediate
What are the two main functions provided by Encodable and Decodable?
Encodable provides encode(to encoder: Encoder) to convert data to an external format.<br>Decodable provides init(from decoder: Decoder) to create an instance from external data.
Click to reveal answer
beginner
What Swift class is commonly used to encode and decode JSON data?
The <code>JSONEncoder</code> class is used to encode Swift types to JSON.<br>The <code>JSONDecoder</code> class is used to decode JSON data back into Swift types.
Click to reveal answer
intermediate
How can you customize the keys used during encoding and decoding?
You define an enum called CodingKeys inside your type that conforms to CodingKey. This enum maps your property names to the keys used in the encoded data.
Click to reveal answer
Which protocol must a Swift type conform to for automatic JSON encoding and decoding?
ACodable
BSerializable
CJSONRepresentable
DEncodableOnly
What does JSONDecoder do?
AConverts Swift objects to JSON data
BConverts JSON data to Swift objects
CValidates JSON syntax
DEncrypts JSON data
How do you specify custom keys for encoding properties?
ABy overriding <code>encode(to:)</code> only
BBy using <code>JSONEncoder.keyMapping</code>
CBy renaming the properties
DBy defining a <code>CodingKeys</code> enum
If a struct conforms to Codable, what must you do to encode it to JSON?
AManually write JSON strings
BCall <code>encode()</code> on the struct directly
CCall <code>JSONEncoder().encode()</code> with the struct instance
DUse <code>JSONSerialization</code> only
What happens if a property is missing in the JSON when decoding?
AThe property is set to nil if optional
BDecoding fails with an error
CThe property is ignored silently
DThe decoder fills it with default values automatically
Explain how the Codable protocol helps in encoding and decoding data in Swift.
Think about how you turn Swift objects into JSON and back.
You got /4 concepts.
    Describe how to customize the keys used when encoding a Swift struct to JSON.
    It's about telling Swift which names to use in JSON.
    You got /4 concepts.