Codable II
Codable: Implementing Codable manually.
Codable II
Codable: Implementing Codable manually.
0
0
Checkbox to mark video as read
Mark as read

We can implement our own logic when encoding/decoding objects. Imagine we have a JSON structure that provides the width and height of a rectangle, but we want to store that information in a CGSize property.

let json: String = """
    {
        "width": 35,
        "height": 25
    }
"""


struct MyRectangle: Codable {
    let size: CGSize

    // 1
    enum CodingKeys: String, CodingKey {
        case height
        case width
    }

    // 2
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        let width = try values.decode(Double.self, forKey: .width)
        let height = try values.decode(Double.self, forKey: .height)

        size = CGSize(width: width, height: height)
    }

    // 3
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(size.width, forKey: .width)
        try container.encode(size.height, forKey: .height)
    }
}

Continue reading

Access to all the content with our plans.

Basic Plan

FREE

Start Now
  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions
Monthly
Yearly

Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy