Comment from java, I try to find a way to sort an array in swift as I did with java. But after some tries, it looks like the behavior (not speaking about the API interface) is different.
In java I was doing something like:
myArray.sort( new Comparator<MyClass>() {
public int compare(MyClass obj1, MyClass obj2) {
... (return 1, -1, or zero)
}
}
And if I returned zero, it was like “I don’t know, let’s see how it compare with other objects”. Meaning that zero does not means obj1 and obj2 are mandatorily together, but that the result of the comparison is undetermined.
In Swift, there is a simple syntax with:
myArray.sort(by: {
... (return true or false)
})
But this implies that I’m always able to determine if the objects are > or <, which is not always the case.
Another syntax, more powerful, and that I was thinking similar to java, is
struct MySorter: SortComparator {
typealias Compared = MyStruct
var order: SortOrder = .forward
func compare(_ s1: MyStruct, _ s2: MyStruct) -> ComparisonResult {
... (return .orderedAscending, .orderedDescending, or .orderedSame)
}
}
But here the .orderedSame seems to behave differently: when two objects are identified .orderedSame, they are considered being at the same level, and the sorter will no more try to compare them with other elements.
Is there something in Swift to get the same algo as in java, with the possibility to say “these two elements are not comparable” ?
A use case example is a case where having a set of object with dependencies (a tree), we have all nodes in an array and we want to order nodes depending on the dependencies (the root of the tree first, and then being sure that we never put a node A before another B if B depends on A.
For instance:
struct Node {
let subNodes: [Node]
}
let node1_1 = Node(subNodes: [])
let node1_2 = Node(subNodes: [])
let node2_1 = Node(subNodes: [])
let node2_2 = Node(subNodes: [])
let node1 = Node(subNodes: [node1_1, node1_2])
let node2 = Node(subNodes: [node2_1, node2_2])
let nodeRoot = Node(subNodes: [node1, node2])
let allNodes: [Node] = [node2_2, node1_1, node1, node1_2, nodeRoot, node2_1, node2]
]
expecting:
nodeRoot, node1, node1_1, node1_2, node2, node2_1, node2_2
or
nodeRoot, node1, node2, node1_1, node1_2, node2_1, node2_2
…
but not
nodeRoot, node1, node2_2, node2, node1_1, node1_2, node2_1
(that I get currently in swift, because the sorter compare node1 & node2_2, found no point of comparison and returns .orderedSame, which then put them together what ever happen next.
I hope I’m clear
Thanks