I have a rows of data in sqlite database in range format as shown in screenshot below.

I have stored all these values in an array as String. Now, I have to sort the objects in an array, so that the result is as following and display it in a table view.
<10 cm
90 - 130 cm
240 - 300 cm
400 - 600 cm
'>700 cm
I have tried out some code.
Sample Code 1:
var arr = ["240 - 300 cm", "400 - 600 cm ", "90 - 130 cm", "<10 cm", ">700 cm"]
var arr1 = arr.sorted{$0 < $1}
But, this approach seems to be working for strings with alpha-numeric characters. So, I have tried another approach.
Sample Code 2:
var arr1 = [NSValue.init(range: NSMakeRange(240, 300)), NSValue.init(range: NSMakeRange(400, 600)), NSValue.init(range: NSMakeRange(90, 130))]
var arr2 = arr1.sorted{$0.rangeValue.location < $1.rangeValue.location}
for range in arr2 {
print("\(range.rangeValue.location) - \(range.rangeValue.length) cm")
}
But, for this approach to work, I have to perform the following operation:
Manipulate the data in the format (for ex. 90 - 130 cm) as per requirement so that I can blend it to fit in NSRange.
For values like <10 cm and >700 cm, I have to handle it separately. May be, by inserting those values in the first index and last index after the array has been sorted, yet to try.
After the array has been sorted, again print the value in a proper format which I have done by using for loop in above sample code.
The approach seems to be working with the trade-off of lots of time consumption and operation. I don't know how the performance will be if there are 100 rows of such data.
My question is, is there better and concise method to sort the data in range format in iOS?
Any help is highly appreciated.
This solution checks the first character of the string. If it's convertible to Int, use the entire string, if not, drop the first character and use that. Then perform a regular compare sorting with option numeric
let arr = ["240 - 300 cm", "400 - 600 cm ", "90 - 130 cm", "<10 cm", ">700 cm"]
let arr1 = arr.sorted { (str1, str2) -> Bool in
let lhs = Int(str1.prefix(1)) == nil ? String(str1.dropFirst()) : str1
let rhs = Int(str2.prefix(1)) == nil ? String(str2.dropFirst()) : str2
return rhs.compare(lhs, options: .numeric) == .orderedDescending
}
print(arr1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With