Search code examples
swiftkotlinkotlin-multiplatform

Where are Swift's constants in Kotlin Multiplatform?


I'm trying to create a number formatter in Swift from Kotlin code in a KMP project. The code looks like this:

    val formatter = NSNumberFormatter().apply {
        locale = NSLocale("US")
        maximumFractionDigits = 2u
        roundingMode = NSNumberFormatterRoundingMode.down
    }

Unfortunately, the last line setting the rounding mode does not work because I invented the down constant. The roundingMode property is of type platform.Foundation.NSNumberFormatterRoundingMode, which is an alias for platform.darwin.NSUInteger, which is an alias for kotlin.ULong. All of this is fine, but, where are the constants I can assign as roundingMode?

The equivalent line in swift would look like:

        formatter.roundingMode = .down

And if I reveal the code for .down I get to see the following:

    public enum RoundingMode : UInt, @unchecked Sendable {

        
        case ceiling = 0

        case floor = 1

        case down = 2

        case up = 3

        case halfEven = 4

        case halfDown = 5

        case halfUp = 6
    }

I guess I can write directly the constant 2 myself in Kotlin code, but is there a better way to replicate these enums/integer values so that the source code is a bit more readable?


Solution

  • The constant you are looking for is NSNumberFormatterRoundDown.

    Kotlin Native does not understand Swift directly but uses Objc. For questions like this, it helps to look at the documentation in ObjC: https://developer.apple.com/documentation/foundation/nsnumberformatterroundingmode?language=objc