Ivan Goremykin
Ivan Goremykin

Reputation: 191

How to extend a generic class for all types that DOES NOT conform to a specific protocol?

I have a generic class:

class MyGeneric<Item>
{
}

I would like to add an extension method for all types that are not, say, Numeric.

Something like this (pseudocode):

extension MyGeneric where Item: !Numeric
{
   func myFuncForNonNumeric()
   {
      print("I am not Numeric!")
   }
}

Is there a way for specifying such constraints?

Upvotes: 0

Views: 108

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

No, there is no way to say "not" in Swift type constraints.

That said, what would you use this for? What algorithm can be applied to the typeclass "not Numeric" that cannot be applied to Numeric types? The typeclass "not Numeric" has no methods on it to use.

This concept is also problematic because types can be conformed to protocols in random places, and over a scope as small as a file. For example, if one module internally conforms a type to Numeric, how should MyGeneric behave in other modules?

How would this behave for MyGeneric<CustomStringConvertible>? Int is CustomStringConvertible, so Item may be an Int in a CustomStringConvertible existential. Does this method exist? (The obvious answer is yes, because CustomStringConvertible is not Numeric, but is that what you mean? How is that useful?)

I want to be clear that all these questions don't imply that your initial desire is wrong-headed or impossible. With careful thought, it might be possible and useful. And in that case, ideally, Swift would be evolved to support it. But it often points to a mismatch between the tool you're looking for and the problem you're really trying to solve, so it's helpful to explore that more.

Upvotes: 4

Related Questions