Equivalent of ObjC class `load` in Swift

I have a SPM package and I would like to run some initialisation code before anything else gets executed.

In ObjC, this is possible to do by using class load. Is this possible to do in some way in Swift?

AFAIK it's recommended that you rely on global lazy initializations,

Thanks for linking that thread! I was looking for that but couldn't find it.

I am not sure if lazy global initialisation would solve my problem, because:

public var runOnce: Void = {
    print("asdfsdf")
}()

still requires that someone references runOnce?

Just to clarify my problem further - I have SPM package with UI components that uses custom font. This font needs to be registered before it is used and I would like to do this in one place if it is possible.

I understood the first time, you basically want your library's initialisation code to be executed on load-time, i.e. before main which is what __attribute__((constructor)) does for C functions. But since you're dealing with UI stuff (font registering) this might not be a good idea, the UIKit classes you'll be calling into might have uninitialized state / broken invariants at that time. Hiddent dependencies like this makes the mechanism so brittle which is why I guess that proposal got rejected.

Still if you want to experiment you can try exposing your library's initialisation function to C using @_cdecl. Then include a .c file with another function marked with that constructor attribute into which you call your library's initisalisation, the compiler & linker should handle the rest. This however forces you to give up on SPM since it doesn't compile C alongside swift (last I heard).

My suggestion here would be to have the act of referencing the font force the invocation of the runOnce function. That is, if the font is itself stored in a static var or static let, have the computation for that font trigger the "run once" operation.

We are using CTFontManagerRegisterGraphicsFont, but I understand your point.

Yeah, we've restructured public API to ensure font is registered appropriately.

Thank you!

Is it not normally done via Info.plist with no code in the app?

The problem is that font is bundled in SPM package and when running package UI tests, font needs to be manually loaded.

If you think there is a better way around it, let me know.