Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swift gotcha with static init #1

Open
AndyDentFree opened this issue Feb 7, 2019 · 0 comments
Open

Swift gotcha with static init #1

AndyDentFree opened this issue Feb 7, 2019 · 0 comments

Comments

@AndyDentFree
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant