1

I have three targets - application and two static libraries (Lets call them as App target, LibA and LibA targets for easy references).

The App target is dependent on the LibA target and LibA target is dependent on LibB target.

In the source files in LibA target, I just

import LibB

to use the types in LibB.

Now, unfortunately, there is a need to use a method from LibA in LibB. This goes against the dependency order.

In C++, you can leave a global function declaration (extern) in LibB and expect it to be defined somewhere else (LibA here). I can just invoke that global function in LibB. The linker will find the function definition in LibA when constructing the executable (by building the App target). This also ensures the compilation of LibA and LibB. The same can be achieved for types using forward declarations of classes.

Is something like this possible in swift? Is there any way to expose a method from LibA to LibB without LibB importing LibA (importing causes a cyclic dependency error) ?

(I understand that I haven't segregated the modules properly, but wanted to know if something like this is possible in swift (since swift is also a compiled language like C++)).

NightFuryLxD
  • 847
  • 5
  • 15
  • 1
    Just because you *can* do something in C++ doesn't mean you should, and throwing a function prototype for `B.cpp` at the top of `A.cpp` outside of a header would never pass code review anywhere I work. What you're looking for, in either C++ or Swift, is called [dependency inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle). – Silvio Mayolo Oct 07 '22 at 13:30
  • I agree with the first part - this is not a good practice. But this question is about understanding swift. You have shared a link, which is a coding principle (based on a cursory reading. I will check it out in detail in sometime), but I was looking for a feature in the swift programming language... For example, C++ provides preprocessor macros (#ifdef) but swift provides the same (#if) in a [slightly different way](https://stackoverflow.com/a/36502874/12791298), but both achieve conditional inclusion of code during compilation. Now, does swift provide something equivalent to C++ extern? – NightFuryLxD Oct 08 '22 at 04:17

0 Answers0