Setup
swift4j is distributed as a Swift package. Add it as a dependency in your Package.swift and import the Swift4j product in any target you want to export to the JVM.
Package.swift
Section titled “Package.swift”import PackageDescription
let package = Package( name: "MyLibrary", platforms: [.macOS(.v14)], products: [ .library(name: "MyLibrary", type: .dynamic, targets: ["MyLibrary"]) ], dependencies: [ .package(url: "https://github.com/scade-platform/swift4j.git", branch: "main") ], targets: [ .target( name: "MyLibrary", dependencies: [ .product(name: "Swift4j", package: "swift4j") ] ) ])Two things to note:
- The library product must be
.dynamic. The JVM loads native libraries at runtime usingSystem.loadLibrary(), which requires a shared library (.so/.dylib). - swift4j requires Swift 5.10 or later for macro support.
Importing in Swift
Section titled “Importing in Swift”In any Swift file that uses the @jvm macro:
import Swift4jThat’s all the setup needed on the Swift side. The @jvm macro and the JNI runtime layer are both part of the Swift4j product.