Home > Software design >  CustomComparator from Java into Swift
CustomComparator from Java into Swift

Time:10-10

I am trying to convert Java code into Swift. I have gone so far but stuck into custom comparator logic. I am wondering how to achieve that in Swift.

class CustomItem {
  var start: Int
  var end: Int
  
  init(start: Int, end: Int) {
    self.start = start
    self.end = end
  }
  
  static func compare_customs(_ content: [UInt8], _ custom1: CustomItem , _ custom2 : CustomItem) -> Int {
    // the logic is implemented here already!
  }
}

var content: [UInt8] = output.getBuffer()

var items = [CustomItem]()
for i in 0..<offsets.count - 1 {
  items[i] = CustomItem(start: offsets[i], end: offsets[i   1])
}
items[offsets.count - 1] = CustomItem(start: offsets[offsets.count - 1], end: output.size())
// Swift Custom comparator logic here??

Trying to convert the following Java custom comparator logic into Swift. Any guidance would be appreaciated.

byte[] content = output.getBuffer();
java.util.Arrays.sort(items, new java.util.Comparator<CustomItem>() {
      @Override
      public int compare(CustomItem custom1, CustomItem custom2) {
        return CustomItem.compare_customs(content, custom1, custom2);
      }
    });

CodePudding user response:

It would be something like

items.sort { CustomItem.compare_customs(content, $0, $1) < 0 }
  • Related