3

First of all I'm trying to execute code in my app (only from my Swift Framework!) when it is loaded into memory.

Normally I would use this ObjC Method to execute Code when my Framework is loaded into Memory.

Is there something equivalent to this in Swift?

static void __attribute__((constructor)) initialize(void){
    NSLog(@"==== Code Injection in Action====");
    /*
    My Code
    */
}

What I have found:

Apple Developer Page regarding this (but it's also only explained in ObjC)

Other Page about Code Injection in general

Any Ideas?

John Smith
  • 573
  • 6
  • 22
  • `__attribute__((constructor))`s run even before `+[NSObject initialize]`, though, @CharlesSrstka, IIRC. – jscs Mar 21 '18 at 15:43
  • @JoshCaswell Yeah, that's why I originally just answered the question; been going back and forth on this. Conceptually it's the same thing, though; how to use Objective-C initialization hooks that aren't available to Swift. – Charles Srstka Mar 21 '18 at 15:45
  • @JoshCaswell Agh, thinking about it some more, you're probably right, this isn't technically the same question. I wonder if I can take back a duplicate vote. – Charles Srstka Mar 21 '18 at 15:46
  • @CharlesSrstka, No worries. I can reopen it myself, but let me ping Martin first. – jscs Mar 21 '18 at 16:16
  • @MartinR: Do you have any thoughts on the above? – jscs Mar 21 '18 at 16:17
  • @JoshCaswell: It still looks like a duplicate to me. There is no `initialize` in Swift, and various approaches to *"I want to execute some code when my framework has been loaded"* have been posted in those Q&As. Also this answer https://stackoverflow.com/a/49099439/1187415 explicitly states that there is no Swift equivalent. – Martin R Mar 21 '18 at 17:06
  • Thanks for your thoughts, @MartinR; I agree we should leave it. – jscs Mar 21 '18 at 17:22

1 Answers1

2

Currently, Swift does not have this functionality. You can either just define an initialization function for your framework and ask your clients to call it before using any other APIs, or you can just mix in an Objective-C file into the project.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60