Simple example of using Boost Framework math functions in Swift

SwiftBoostExample

I’m new to Swift and it wasn’t immediately clear how to easily import and use Boost Framework functions, so here’s a very basic example for anyone else wanting to do this.

Requirements

  • Xcode
  • Swift 5.7+

Additional Notes

Quick Start

  • Clone the repository
  • Load the included Workspace in Xcode: ./SwiftBoostExample.xcworkspace
  • Update signing & capabilities if needed
  • Select destination
  • And run!

Reference

Installing Boost via CocoaPods (optional)

I found it easiest to install Boost using CocoaPods since it automatically creates a Workspace and .xconfig file with the appropriate header search paths. Here’s how to do that:

  • Install CocoaPods. See instructions here: https://cocoapods.org/
  • Create a Podfile with the following contents:

target 'SwiftBoostExample' do
  use_frameworks!
  pod 'boost', '~> 1.51.0'
end
  • Open terminal and run pod install in the repository root. It may take a very long time to complete the first time.

(Note: Boost 1.51 is rather old but other pod versions were throwing errors during compilation due to missing includes in the podspec. See https://github.com/CocoaPods/Specs/tree/master/Specs/9/9/d/boost for available podspec versions)

Updating compiler flags

  • Add the following flags to Build Settings -> Other Swift Flags:

-enable-experimental-cxx-interop
-I./BoostFramework

  • If you didn’t install with CocoaPods then you also need to add the Boost path to Build Settings -> Swift Compiler - Search Paths -> Import Paths

Create BoostFramework group, header and modulemap

BoostFramework.hpp example

#ifndef BoostFramework_hpp
#define BoostFramework_hpp

#define BOOST_NO_EXCEPTIONS

#include <stdio.h>
#include <boost/math/special_functions/prime.hpp>
#include <boost/math/special_functions/zeta.hpp>
#include <boost/throw_exception.hpp>

uint32_t prime(uint32_t n) {
    return boost::math::prime(n - 1);
}

double zeta(double z) {
    return boost::math::zeta(z);
}

void boost::throw_exception(std::exception const & e){
  //TODO: handle exception
}

#endif /* BoostFramework_hpp */

module.modulemap

module BoostFramework {
    header "BoostFramework.hpp"
    requires cplusplus
}

GitHub

View Github