Limit parameter argument parameter for base class in Swift

Let's assume the following setup:

class BaseClass<T> { }

class SubClass<T>: BaseClass<T> { }

infix operator >-- { associativity left }

func >-- <T>(lhs: BaseClass<T>, rhs: SubClass<T>) {
    // do something here
}

      

I am looking for a way to exclude SubClass

from use as an argument lhs

with an operator >--

. It would rather be a negative type constraint for a generic argument - i.e. T: BaseClass where T != Subclass

:

func >-- <T, B: BaseClass<T> where B != SubClass<T>>(lhs: B, rhs: SubClass<T>)

      

But it doesn't seem like there is an argument !=

that you can specify as a negative type constraint for the generic. Is there a way to do this?

Thank!

EDIT:

I think that I can actually make the question less complicated - I think the following setup addresses the exact same problem, but without any distracting details:

class BaseClass { }
class SubClass: BaseClass { }

// This is what I want to be able to do, but don't know how
// or if it is possible:
func doSomething<B: BaseClass where B != SubClass>(arg: B) { }

      

Hopefully I didn't just confuse everyone the most, but the "infix operator" part and the fact that it BaseClass

was generic BaseClass<T>

is not very important to the question ...

+3


source to share


1 answer


You cannot prevent subclass instantiation substitution for a superclass instance at the compiler level, as you are trying to do, because that substitution is at the heart of polymorphism itself.

You are of course free to throw at runtime if the parameter of dynamicType

this parameter is not a superclass:



func doSomething(arg: BaseClass) {
    if !(arg.dynamicType === BaseClass.self) {
        fatalError("die die die")
    }
    println("ok")
}

      

+1


source







All Articles