I need to set up some relatively simple IPC for Mac and it needs to be done using UNIX domain sockets. I'm brand new to Swift so while I know this is possible I'm struggling even create my client and server. I have found a few useful resources for using UNIX domain sockets in other languages (Like this one: IPC using Unix Domain Sockets) but anything based in swift that I've found is more than I can follow at the moment in the brand new language. If someone could explain it like I'm 5 or at least point me in the right direction I'd appreciate it.
-
1Hey Tyler, welcome to the site. This question is a bit too broad to be neatly answered in the Q/A format here. Try breaking it down bit by bit, and we can help you tackle the more concrete issues you run into along the way. For the most part, the actual functions and everything that you'll need are going to be the same as the example you linked. However, since C heavily relies on pointers, you'll see that many of these bridge into Swift using Swift's `Unsafe(Mutable)(Buffer)(Raw)Pointer` types, which can sometimes be tricky to work with. – Alexander Oct 16 '21 at 15:36
1 Answers
If you are more familiar with other languages - do it using other languages, and then incorporate into Swift.
Personally, I beleive that each language should be used to the things it doing best. Swift is not really doing best any of low-level stuff, but it could use libraries written in other languages, that are actually good in such things.
You can write the library on C or C++, working with sockets as you might find convenient, then make the Objective-C/C++ wrapper around it, then use the bridging-header to import Objective-C/C++ wrapper and use it from Swift code.
It may be a bit overhead in code size, but it would look nicer and be debuggable better, than having all this ugly Unsafe*** stuff in Swift.
For 5-y.o section: 0) Create 2 projects: Objective-C/C++ static library, Swift console app
- Write some nice API in .h file into lib, like "create, read, write" functions, implement them using resources you found in C or C++.
- Write some other .h file into lib with Objective-C/C++ API. You can really keep names and arguments, just change types to be NS* (std::string or char* -> NSString* and etc), and make this looks like class. Implement passing to C/C++ part in .m/.mm relevant file.
- Build the project 1, you should get an .a (static) library.
- Add a Bridging Header (it is a term, you could google it) to your Swift app, import there a Objective-C/C++ header. Add the .a library to Build Phases (Link Binary with Libraries). Use Objective-C/C++ class you created like it is Swift class for unix socket IPC.

- 1,207
- 8
- 17