Skip to content

Swift gotcha with static init #1

@AndyDentFree

Description

@AndyDentFree

I'm using a pattern to register the decoding factories that works like this, initialising a static property:

  private static let typeCode = HierCodableFactories.Register(key:"BB") {
    (from) in
    return try? BaseBeast(name:from.read())
  }

However, that's a C++ idiom which is not safe in Swift.

As I found out in my main app's use of this approach, it doesn't work if the first thing you try to do is decode data - none of the factories are registered.

The problem is that the Swift static and class variables are _lazily initialised which means until you refer to them, the closure which does the factory registration is not done.

There are a couple of ways to handle this, cleanest is to move to a separate registration function for all your types and change the typeCode into just a simple assignment. Documenting in this issue because am in shipping hell at present and won't have time to polish this sample for a bit.

Also, thought the issue was an interesting enough gotcha that it deserved a full writeup here for future reference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions