3

The Swift Package Manager (SPM) allows support for different platforms (e.g., iOS, macOS). I'm adapting a Swift library to use SPM, and the need is for some of the code for iOS and macOS to be shared, but to have some differences as well.

I've seen a similar example of this with the Facebook libraries: https://github.com/facebook/facebook-ios-sdk/blob/master/Package.swift In that case, they use multiple targets, each with its own (independent) code. This is not an example of platform dependency, rather of target dependency.

I see two paths forward:

1) Have separate library targets for iOS and macOS-- and use a similar approach to Facebook, but the bulk of the code would be shared across the targets. I'm not entirely sure if SPM allows code shared across targets. A downside here is purely in terms of syntactic sugar-- naming differences. It seems unfortunate that you'd have to import say "MyLibrary_iOS" on iOS and "MyLibrary_macOS" on macOS.

2) Have a single target for iOS and macOS, but embed conditional compilation within the source code to conditionally include/exclude specific files. This doesn't have the naming issue as above. But it seems unclean to have to do this conditional compilation.

Any other suggestions? Thanks!

Chris Prince
  • 7,288
  • 2
  • 48
  • 66
  • It looks like my approach 1) may be possible, but with code sharing done via a dependent library. See https://stackoverflow.com/questions/59652708/two-almost-identical-targets-in-vapor-xcode-project?rq=1 and see https://stackoverflow.com/questions/60067701/how-to-resolve-swift-package-manager-target-overlapping-sources-error – Chris Prince May 11 '20 at 13:46
  • See also https://forums.swift.org/t/sharing-sources-between-different-targets/14542 – Chris Prince May 11 '20 at 13:47

1 Answers1

1

Wait for the upcoming release of Swift 5.3. This has been added via SE-0273.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Cool. Let me try to understand the use of SE-0273 for my case. I'd establish three targets, call them "Common", "iOSSpecifics" and "MacOSSpecifics"-- and in the latter of these reference the dependent .swift files. I'd then reference the "Common" target unconditionally, and reference the two other targets conditionally from my main target of interest. Does that sound right. – Chris Prince May 11 '20 at 23:01
  • I'm now using this in Xcode 12 beta 6. Takes a bit of arm wrestling for some reason to get the build to happen without errors, but it's working! – Chris Prince Aug 29 '20 at 17:00
  • @ChrisPrince do you have an example of this? I'm struggling to picture exactly how this works! – simonthumper Sep 30 '20 at 11:14
  • Take a look at this: https://github.com/SyncServerII/ServerAccount/blob/master/Package.swift and see if it helps. I exclude three dependencies when building for iOS (Kitura, HeliumLogger and Credentials). – Chris Prince Oct 02 '20 at 02:35