Swift on Android: one Sudoku engine under two native apps
Cool Sudoku has two native apps. The iPhone app is SwiftUI, the Android app is Kotlin and Compose. The rules of the game are written once, in a Swift package, and the Android app calls that package through JNI. This is what the border between the two languages looks like in a real project, what it weighs, and a bug on it that no compiler could see.
What is shared
The engine is a Swift package. Two of its modules, OMSudokuCore and OMSudokuGameplay, hold puzzle generation, the rules of a game, the undo history, hints and the Daily Puzzle. Together they are 21 files and 2,733 lines.
The iPhone app lives in the same package and calls these types directly. Android gets them through a third module, OMSudokuJavaBridge, which is built as a dynamic library.
Everything above the engine on Android is Kotlin: 122 files and about 23,000 lines of Compose screens, view models, storage, networking, billing and ads. Saving a game is Kotlin too. The engine hands over a snapshot and the app stores it.
Sharing stops at the engine. Achievements, statistics and the rules around the Daily Puzzle exist a second time in Kotlin.
The Daily Puzzle shows what one engine gives. Both apps build it on the phone from a date key, a difficulty and a salt, and both run the same generator. A test compares the board for one fixed date with a string of 81 digits, and each side has a test that pins the salt.
A facade with boring types
The bindings come from swift-java. Its jextract tool reads Swift source and writes two halves of a bridge: Swift functions with JNI names, and Java classes that call them. The default mode of the tool needs the Foreign Function and Memory API of JDK 22, which Android does not have. The JNI mode was added for platforms like Android, so the project sets "mode": "jni" in swift-java.config.
The hand-written part is one file, SudokuJavaBridge.swift, 281 lines of plain Swift with no annotations. A comment on the class lists what it deliberately avoids: protocols, existentials, nested arrays, Set, Data, async methods and enums with associated values. Richer Swift types are flattened before they reach the border. The result of a move is an enum with associated values in the engine and a status string in the facade. A missing coordinate is -1. The cells a hint highlights travel as one flat array of triples: page, row, column.
| Swift | Java |
|---|---|
Int, Int64 |
long |
Bool |
boolean |
String |
String |
[Int] |
long[] |
init?, T? |
Optional<T> |
| struct or class | a class that holds a pointer |
From that one file the tool generates 1,530 lines of Swift and 1,438 lines of Java. The library exports 76 Java_* symbols. Both halves are committed, each in its own repository, and they have to match symbol for symbol.
One move, from tap to engine
The player taps a digit. Kotlin calls the generated Java class:
val result = game.place(value.toLong(), row.toLong(), column.toLong(), arena)
The Java class is a thin wrapper around a native method that takes the address of the Swift object:
// Signatures only.
public SudokuMoveResultDTO place(long value, long row, long column, SwiftArena swiftArena)
private static native long $place(long value, long row, long column, long selfPointer)
On the Swift side the generated function carries the JNI name. Shortened:
@_cdecl("Java_com_coolsudoku_swift_SudokuJavaBridge__00024place__JJJJ")
public func Java_com_coolsudoku_swift_SudokuJavaBridge__00024place__JJJJ(
environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass,
value: jlong, row: jlong, column: jlong, selfPointer: jlong
) -> jlong {
// ... converts the three jlong arguments to Int64 ...
let selfPointerBits$ = Int(Int64(fromJNI: selfPointer, in: environment))
let selfPointer$ = UnsafeMutablePointer<SudokuJavaBridge>(bitPattern: selfPointerBits$)
guard let selfPointer$ else {
fatalError("selfPointer memory address was null in call to \(#function)!")
}
let result$ = UnsafeMutablePointer<SudokuMoveResultDTO>.allocate(capacity: 1)
result$.initialize(to: selfPointer$.pointee.place(
value: Int(value$indirect), row: Int(row$indirect), column: Int(column$indirect)))
let resultBits$ = Int64(Int(bitPattern: result$))
return resultBits$.getJNILocalRefValue(in: environment)
}
And this is the method it calls, the only hand-written Swift in the chain:
@discardableResult
public func place(value: Int, row: Int, column: Int) -> SudokuMoveResultDTO {
let result = game.apply(.place(value: UInt8(clamping: value), at: Coordinates(row: row, column: column))) ?? .invalidPosition
return Self.resultDTO(result)
}
Two things here are not obvious if you come from iOS. A Swift Int is a Java long, so the Kotlin adapter is full of .toLong() and .toInt(). And the result struct is not copied across the border. The generated function allocates it on the Swift heap and returns its address as a number. The Java object holds that pointer, and an array of structs arrives as an array of addresses.
Memory belongs to an arena
That pointer is why almost every call takes a SwiftArena. A value that Swift returns stays alive until its arena frees it. swift-java has two kinds. SwiftArena.ofConfined() frees everything at the end of a try block. SwiftArena.ofAuto() frees an object when the Java garbage collector gets to it.
Cool Sudoku creates one automatic arena per game. The Javadoc of swift-java calls the automatic kind the less reliable of the two and recommends the confined one. The project still uses the automatic one, so the memory of a game is returned whenever the garbage collector runs.
Errors do not cross the border
The facade has no throwing functions. A call that fails is a failable initializer that returns nil, and Java sees Optional.empty(). The Kotlin adapter turns that into an exception in one place and into null in the others.
This is where the bug was. Restoring a saved game passed the number of cells, 81, where the Swift side expects the side of the board, 9. Both are a long. Swift rejected the snapshot and returned nil, and the app did what it does with nil: it started a fresh board. Every saved game was rejected on restore, the classic game quietly began again from an empty board, and nothing crashed. The cause was one number.
place returns a status string, so a wrong move has a name: incorrect, fixedCell. The initializers return only nil, and nil does not say which argument was wrong.
Threads
Creating a game, computing a hint and building the Daily Puzzle run on Dispatchers.Default. Moves, erasing and undo are called synchronously from the view model. The bridge class has no locks and is not Sendable. The view model pauses moves while a hint is being computed.
Building the library
The library is built with the Swift SDK for Android, version 6.4, and NDK 28.1. The command from the project's README:
export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/28.1.13356709"
swift build --swift-sdk swift-6.4.0-RELEASE_android \
--triple x86_64-unknown-linux-android26 -c release \
--target OMSudokuJavaBridge
The README shows it for x86_64. The library inside the app is the arm64 build for API level 26, with the Swift runtime linked statically and the result stripped with llvm-strip --strip-unneeded.
Static linking means the app has no libswiftCore.so. The bridge depends on system libraries and on libc++_shared.so, which comes from the NDK and has to sit next to it.
The generated Java classes try to load a separate libSwiftJava.so when a class initializes. With the runtime linked into the bridge, that library does not exist, so the binding script removes the line with sed.
R8 renames classes, and JNI finds them by name. Two rules keep the generated classes and the swift-java runtime as they are:
-keep class com.coolsudoku.swift.** { *; }
-keep class org.swift.swiftkit.** { *; }
The README adds one more rule, for people: after a change to the bridge, test a minified release build as well as a debug one.
Google Play requires apps that target Android 15 or later to support 16 KB memory pages on 64-bit devices. Both native libraries in the app have their load segments aligned to 16 KB.
The weak point is that the library is not built together with the app. Gradle does not compile Swift, and neither does CI, which builds the Kotlin side and runs the Swift tests on macOS. The .so is a binary committed to the Android repository. A change in the engine reaches Android only after someone rebuilds the library and commits it, and it exists for one ABI, arm64-v8a.
What it weighs
| What | Size |
|---|---|
| Engine source, Core and Gameplay | 2,733 lines |
libOMSudokuJavaBridge.so, stripped |
62.6 MB |
| The same library, compressed inside the app bundle | 23.6 MB |
| App bundle of internal build 118 | 37.1 MB |
The bridge is about 64% of the bundle.
The code section of the library is 16.6 MB. The read-only data is 37.5 MB, and the binary carries ICU data and Foundation symbols. Foundation is imported in one file of the engine, the Daily Puzzle generator, for Date, Calendar, TimeZone and String(format:). Android does not use that path at all: Kotlin builds the date key and passes a ready string.
Nobody has measured the library without Foundation yet, so I cannot promise a number. That one import is the place to start.
What the tests do not cover
The bridge is tested on macOS. Seven Swift tests check the shape of a snapshot, a signed seed, the command history, notes and the Daily Puzzle.
The Android unit tests run on the JVM and use fakes in place of the engine, and the folder for device tests is empty. No test calls Swift on Android. The 81 and 9 bug is the kind that lives in that gap: it was in the Kotlin adapter, the one layer that only a real device runs against the real engine.
Before you try this
swift-java is a dependency on the main branch, with no version. The build repeats only because Package.resolved pins a revision.
The project needs two toolchains on one machine. Xcode builds the iPhone app and runs the tests, because the open-source toolchain has no SwiftData macros and stops at @Query. The open-source toolchain with the Android SDK builds the library.