Sridhar Sridhar - 7 months ago 28
Swift Question

Custom sorting in Swift

I have to implement sorting functionality in my app. Kindly consider the following logics.

I want to sort the array RangeClass objects based on the given input (say 50).

class RangeClass:NSObject {
var start:Int64!
var end:Int64!

convenience init(s:Int64,e:Int64) {
self.init()
self.start = s
self.end = e

}


var test1 = RangeClass(s: 50, e: 62) // 50 is in the range
var test2 = RangeClass(s: 12, e: 26) // 50 is not in the range
var test3 = RangeClass(s: 78, e: 89) // 50 is not in the range
var test4 = RangeClass(s: 35, e: 89) // 50 is in the range
var test5 = RangeClass(s: 11, e: 74) // 50 is in the range
var test6 = RangeClass(s: 26, e: 62) // 50 is in the range

var testArr:NSArray=[test1,test2,test3,test4,test5,test6]

testArr[0]
testArr[0]


print(testArr)


testArr.sortedArrayUsingComparator { (
testA, testB) -> NSComparisonResult in

let p1 = testA as! RangeClass
let p2 = testB as! RangeClass
// check whether both are in the range
if p1.start > 50 && p1.end < 50 && p2.start > 50 && p2.end < 50
{

if (p1.start > p2.start) {
return NSComparisonResult.OrderedDescending;
} else {
return NSComparisonResult.OrderedAscending;
}

}else if (p1.start > 50 && p1.end < 50){
return NSComparisonResult.OrderedAscending
}else if (p2.start > 50 && p2.end < 50){
return NSComparisonResult.OrderedDescending
}else{
if (p1.start > p2.start) {
return NSComparisonResult.OrderedDescending;
} else {
return NSComparisonResult.OrderedAscending;
}
}

}


I want to the output like


test5,test6,test4,test1,test2,test3


ie Objects which are in the Range should come first and which are not is the range joins last.

Answer

I'm not sure that this algorithm catches all cases but at least that one in the question.

let refNum : Int64 = 50

let sortedArray = testArr.sort { (rangeA, rangeB) -> Bool in
  let a = (rangeA.start...rangeA.end).contains(refNum)
  let b = (rangeB.start...rangeB.end).contains(refNum)

  switch (a, b) {
  case (true, true), (false, false) : return rangeA.start < rangeB.start
  case (true, false) : return true
  case (false, true) : return false
  }
}

print(sortedArray)
Comments