DEV Community

Mikhail Isaev
Mikhail Isaev

Posted on

Swift on Android: JNIKit 2.11.0: Automatic Memory & 2D Arrays

The ecosystem for Swift on Android just got a significant upgrade with the release of JNIKit 2.11.0. This library simplifies JNI interaction, and this latest version focuses on two major pain points: robust memory management and expanded data structure support.

Automatic Memory Control

The days of manually managing JNI references are over.

  • JObject now automatically deletes its underlying jobject on deinit.
  • This logic has been extended to JClass, JClassLoader, and JObjectArray.
  • Key Takeaway: You can now rely entirely on Swift's deinit for memory management. No more manual deletion or worrying about reference leaks.

Note for Upgraders: This is a breaking change if you previously handled memory manually. Also, the internal method env.callObjectMethodPure has been updated—check the release notes if you use it directly.

1D & 2D Array Support

Working with Java arrays is now more Swift-like than ever.

1D Arrays (e.g., [Int8], [Float], [Double]):

  • Easy initialization from a Swift Array: JIntArray([1, 2, 3])
  • Efficient iteration to avoid copying large arrays:
for value in intArray {
    Log.d("value: \(value)")
}
Enter fullscreen mode Exit fullscreen mode

New: 2D Array Support! 🎉 (e.g., [[Int32]], [[Double]])
This is crucial for many Android APIs (like ColorStateList).

  • Initialize directly from a nested Swift array: JIntArray2D([[1, 2, 3], [4, 5, 6]])
  • Iterate or convert back to a Swift array with ease.

Passing arrays to Java methods is now trivial:

// No need to manually create wrapper objects
object.callVoidMethod(name: "send1DArray", args: [1, 2, 3])
object.callVoidMethod(name: "send2DArray", args: [[1, 2, 3], [4, 5, 6]])
Enter fullscreen mode Exit fullscreen mode

Enhanced Debugging

Logging for global reference creation/deletion has been greatly improved, making it easier to trace memory issues during development.

Links:

If you find JNIKit useful, giving it a star on GitHub helps others discover it and supports the project!

I'm happy to answer any questions and hear about your experiences using Swift for Android.

Top comments (0)