Codable - get source code for automatically generated init(from:) and encode(to:) methods

I don't think you read Williams comment correctly. He was referring to a shortcut for generating the init(from:) and encode(to:) methods that Swift automatically synthesizes for Codable types. He said that it would be like the shortcut for generating the default member-wise initializers for structs. As I explained in my original post, this would be useful because then you could make small changes in the places that you need to without typing out the entire methods manually.

Yes, what Iā€™m referring to is if you have a type like:

struct Foozle {
    var flim: Bool
    var flam: CGFloat

In Xcode you can select the word Foozle, right-click, and from the pop-up menu select Refactor ā–¶ Generate Memberwise Initializer.

This will give you:

struct Foozle {
    internal init(flim: Bool, flam: CGFloat) {
        self.flim = flim
        self.flam = flam

    var flim: Bool
    var flam: CGFloat



I see you're on macOS Big Sur :smirk:. The context menus do look nice. Also, you may already know this, but you can also command-click on the declaration of the struct to generate the initializer.

Ah, thank you. I rarely use those but should learn to more.

It sounds like this part is based o open source part of Swift itself and is something we could contribute to:

Ah yah, looks like the relevant source is here:

With that specific function being RefactoringActionMemberwiseInitLocalRefactoring


Shame this stuff is all only do-able by modifying the compiler. Steep barrier to entry.

Maybe some of the simpler ones are possible with SourceKit and an Xcode Extension?

Did you link to the code for generating meberwise-initializers or for generating the Codable methods? This code looks quite arcane.

The linked lib/IDE/Refactoring.cpp has tools for performing the refactoring operations in the Refactor menu; the code for synthesizing Codable conformance can be found in lib/Sema/DerivedConformanceCodable.cpp

1 Like

What about splitting the struct declaration into 2 parts:

  1. Superclass with properties where compiler-sythesized implementation is sufficient
  2. Subclass with properties that need custom treatment

[2] then can delegate most of the work to [1]'s implementations.

Good suggestion, but in this case I'm using a struct.

Ah, I have totally missed that :confused:

Terms of Service

Privacy Policy

Cookie Policy