1

I have a class with a contructor that with NSOrdered set as param, my secondary contructor will receive a collection and a comparator. I am not able to initiale NSOrdered as no contructors exists that converts array to NSOrderedSet

class IOSSortedSet<T>(private val list: NSOrderedSet) : SortedSet<T> {

    constructor(
        comparator: Comparator<in T>,
        collection: Iterable<T>
    ) : this(NSOrderedSet(collection.sortedWith(comparator).toList())). //Incorrect

Basically the line NSOrderedSet(collection.sortedWith(comparator).toList()) is incorrect. Please help me with the correct syntax.

This is the only constructors available on Kotlin: enter image description here

Romit Kumar
  • 2,442
  • 6
  • 21
  • 34

1 Answers1

0

This question, as is the case with several others relating to how to write Kotlin/Native code for iOS, is best solved by referencing Apple's Objective-C documentation for NSOrderedSet (instead of the Swift documentation).

This shows various options for creating NSOrderedSet, and note that these are all class methods (annotated with a +) as opposed to instance methods (annotated with a -). (Having a basic understanding of Objective-C and how to read the language can be quite helpful in this case.)

Apple NSOrderedSet Objective-C Documentation showing how to create NSOrderedSet objects

Since these are class methods, in Kotlin, these can be found on the .Companion object of NSOrderedSet:

Android Studio code completion for Kotlin/Native NSOrderedSet.Companion

Since you mentioned creating an NSOrderedSet from an array, I would guess that the orderedSetWithArray method might be what you're looking for.

There are two variations of this method: one that takes just an array (or a List in Kotlin), and another that takes an array along with a range and boolean indicator for copying items or not.

Sample Kotlin code with IDE pop-over illustrating possible arguments for the orderedSetWithArray method

While sometimes it can be possible to dig through the Kotlin/Native header files (at least, I haven't found an effective way to search through these yet...), in this case, the Foundation class definitions appear to be quite spread out, so I'd recommend using the Objective-C documentation as a starting point instead.

Kotlin/Native Foundation APIs for NSOrderedSet

Derek Lee
  • 3,452
  • 3
  • 30
  • 39
  • If you want to dig deeper, I also published a blog post on writing iOS-platform-dependent code using Kotlin with KMM's expect/actual: https://artandscienceofcoding.com/science/avoid-this-kmm-technique/ – Derek Lee Sep 22 '22 at 04:41