Today I spent one hour to get myself educated on Array type.
I have the following class in one of my app:
class PathNode: Hashable, Comparable, CustomStringConvertible {
var name: String!
var path: String!
var children: [PathNode]?
static func == (lhs: PathNode, rhs: PathNode) -> Bool {
lhs.name == rhs.name
}
static func < (lhs: PathNode, rhs: PathNode) -> Bool {
lhs.name < rhs.name
}
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(children)
}
/// Sort child nodes.
func sort() {
if let children = self.children {
children.sort()
for child in children { child.sort() }
}
}
// other members...
}
The problem is in the sort function. I found out in my outline view the result is not sorted even though I did call sort on the root node.
After about one hour's frustration, I came to realize that I forgot one import fact about the array type in Swift - it's a value type!
I have to adjust sort function to the following code:
/// Sort child nodes.
func sort() {
if self.children != nil {
self.children!.sort()
for child in self.children! { child.sort() }
}
}
That's not an elegant way of writing code! Is there any other way to get a 'reference' to an array in Swift?