How to Make a Library with Xcode

A few months ago, I asked a question on Hacking with Swift about how to extract code from an existing project into a library. This is a thing that, over the course of many years of developing Java applications, I find myself doing often. I solve a problem for one project, then get to another project and realize I have to solve the same problem, so I rewrite the solution to be reusable. I found myself in the same situation with some Swift projects, and I wanted to do the same thing. I know it’s possible — there are zillions of libraries out there to let you do useful things — but I couldn’t find any reference documentation or tutorials on how to do it.

Nobody responded. Well, not nobody, but the only reply I got was along the lines of, “This other guy at this one website once did something almost like that, so maybe ask him?”

Now, months later, I searched on an entirely different question (what’s the difference between an Xcode workspace and a project?) and that has led me to a partial answer to a couple of entangled questions.

First: making a library. So, the thing to do is to make a new project and say that it’s multiplatform and a Swift package. This makes Xcode (version 12) create a project that has files and targets laid out the right way. Just make sure that objects (structs, classes) and methods (functions) are declared public so that they can be seen from outside the library and you’re good to go. Extracting code? Well, I haven’t found a good way to do that, yet. Certainly there’s nothing anywhere close to as clean as selecting a class or struct, right clicking, and selecting “move to…” You know, like Java developers have had for 20 years or so.

Second, and a bonus tip: making an iOS program into a multiplatform app that will also run on a Mac. Here, the thing to do is to tell Xcode to make a new project that is multiplatform and an application. This will, again, lay out the files properly. Then, in the shared code group, add all your actual code. Finally, you can specialize the layout and behaviors with pragmas. Good luck finding documentation for all the available tests you can make, but here’s a hint: #if os(macOS). Yay, it’s like it’s 1996 again and you’re writing C++!

Published by pirateguillermo

I play the bagpipes. I program computers. I support my family in their various endeavors, and I enjoy my wonderful life.

Leave a ReplyCancel reply