Q:

Swift operator and inheritance

I have redefined the > operator in an inheriting class but the system still calling the > of the parent class. Here is my parent
class :
class GenericModelClass : NSObject {
    var subElementArray = [GenericModelClass]()
    func orderSubElements () {
        self.subElementArray.sortInPlace({return $0 > $1})
    }
}
func > (lhs: GenericModelClass, rhs: GenericModelClass) -> Bool {
    print ("Use my > function on GenericModelClass (real class is \(lhs.dynamicType))")
    return lhs.uniqueID() > rhs.uniqueID()
}

Here is the inheriting class :
class Chapter: GenericModelClass {
}
func > (lhs: Chapter, rhs: Chapter) -> Bool {
    print("Use my > operator on chapter")
    return lhs.number > rhs.number
}

But when I call the orderSubElements function with Chapter objects in the subElementArray, the > being called is the one from GenericModelClass. So in the log I have :

Use my > function on GenericModelClass (real class is Chapter)

Do you have an idea how I could get orderSubElements to use the correct operator ? If I have chapters in the subElementArray array, I want to call > for chapters

A:

Operators are not dispatched dynamically. The implementation of > is picked by the compiler using the information available at the call site.
You can get around this by defining a method in GenericModelClass to do the comparison
class GenericModelClass
{
    // ... other stuff ...

    func isGreaterThan(other: GenericModelClass) -> Bool
    {
        return self.uniqueID() > other.uniqueID()
    }
}

And overriding it in Chapter
class Chapter
{
    // ... other stuff ...

    override func isGreaterThan(other: GenericModelClass) -> Bool
    {
        guard let otherChapter = other as? Chapter
        else
        {
            return super.isGreaterThan(other)
        }
        return self.number > other.number
    }
}

The operator becomes 
func > (lhs: GenericModelClass, rhs: GenericModelClass) -> Bool 
{
    return lhs.isGreaterThan(rhs)
}

That answers the question as asked but there is a bit of a design smell indicated by the need to check and cast the type of the parameter and this is that you are mixing two concepts of comparison in one array and sorting it. Your model probably needs to be a bit more sophisticated ie. the concept of ordering of GenericModelClass objects needs to understand the different kinds of object and do its ordering accordingly. e.g. put all the chapters after the preface but before the index etc.

