Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine configuration in Swift code using Swift Package Manager

I'm creating an application using Swift Package Manager and I need to know the configuration of which the project was built under, i.e Debug or Release. I'm trying to stay away from using the .xcodeproj file. Please, someone let me know if this is possible. I'll paste a simple example below, but just know if there's a better way to handling configuration besides the code below, please submit as answer.

Example:

// main.swift

#if DEBUG
  print("Im in Debug!!")
#else
  print("Im in Release!!")
#endif
like image 256
Fabian Buentello Avatar asked Apr 10 '17 19:04

Fabian Buentello


People also ask

How do I run Swift package manager?

swift in its directory produces an executable. Running the swift build command starts the Swift build system to produce the Dealer executable, which can be run from the . build/debug directory. The complete code for the Dealer package can be found at https://github.com/apple/example-package-dealer.

How do I use Swift package manager with Xcode?

Open your Xcode project, navigate the File tab within the macOS bar, and click on “Add Packages”. In the Add New Package window, you can select from recently used or Apple Swift Packages. Alternatively, you can search for a package via the name or the URL to the Github page.

Where can I find Swift packages?

Support for Swift packages in Xcode builds on the open-source Swift Package Manager project. To learn more about the Swift Package Manager, visit Swift.org and the Swift Package Manager repository on GitHub.

How do I add a dependency to a Swift package?

To add a package dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter its repository URL.


1 Answers

As of Swift 3.1, the Package Manager doesn't offer the option to customize build settings in the Package.swift file (this feature is part of the team's roadmap for Swift 4). However, you can use the -Xswiftc flag to pass custom build settings to the compiler when you invoke swift build or swift test.

To set the DEBUG flag in debug mode, invoke swift build like this:

swift build --configuration debug -Xswiftc "-D" -Xswiftc "DEBUG"

And for release builds you would do the usual:

swift build --configuration release

There is also -Xlinker and Xcc to pass flags to the linker and C compiler, respectively.

like image 136
Ole Begemann Avatar answered Oct 06 '22 22:10

Ole Begemann