IamMashed IamMashed - 6 months ago 63
Swift Question

Sort Array with NSRange in swift both by length and location

I am trying to sort an Array of NSRanges in swift both by length and location:

var allranges = [NSRange?]()
allranges.append(NSRange(location: 3, length: 5))
allranges.append(NSRange(location: 9, length: 2))
allranges.append(NSRange(location: 9, length: 1))
allranges.append(NSRange(location: 24, length: 5))
allranges.append(NSRange(location: 16, length: 9))
allranges.append(NSRange(location: 11, length: 6))

allranges.sortInPlace{ $0!.location < $1!.location && $0!.length < $1!.length}
print(allranges)


this is what I have printed:

[Optional((3,5)), Optional((9,2)), Optional((9,1)), Optional((24,5)), Optional((11,6)), Optional((16,9))]

but I want this instead:

[Optional((3,5)), Optional((9,1)), Optional((9,2)), Optional((24,5)), Optional((11,6)), Optional((16,9))]

please help!

Rob Rob
Answer

You presumably want to sort by location, and if location is the same, then sort by length, e.g.:

var allranges = [NSRange]()
allranges.append(NSRange(location: 3, length: 5))
allranges.append(NSRange(location: 9, length: 2))
allranges.append(NSRange(location: 9, length: 1))
allranges.append(NSRange(location: 24, length: 5))
allranges.append(NSRange(location: 16, length: 9))
allranges.append(NSRange(location: 11, length: 6))

allranges.sortInPlace{ $0.location < $1.location || ($0.location == $1.location && $0.length < $1.length) }

Or, if it complains that that expression is too complicated:

allranges.sortInPlace{
    if $0.location < $1.location {
        return true
    } else {
        return $0.location == $1.location && $0.length < $1.length
    }
}
Comments