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?
✗ Incorrect
The
Codable protocol combines Encodable and Decodable for easy JSON encoding and decoding.What does
JSONDecoder do?✗ Incorrect
JSONDecoder converts JSON data into Swift objects.How do you specify custom keys for encoding properties?
✗ Incorrect
Defining a
CodingKeys enum lets you map property names to custom keys.If a struct conforms to
Codable, what must you do to encode it to JSON?✗ Incorrect
Use
JSONEncoder().encode() to convert the struct to JSON data.What happens if a property is missing in the JSON when decoding?
✗ Incorrect
If the property is optional, it becomes nil; otherwise decoding fails.
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.