简体   繁体   English

如何为不符合特定协议的所有类型扩展通用类?

[英]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 . 我想为所有非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? 有没有办法指定这种约束?

No, there is no way to say "not" in Swift type constraints. 不,在Swift类型约束中没有办法说“不”。

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. 类型类“ not Numeric”没有使用任何方法。

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? 例如,如果一个模块在内部使类型符合Numeric,则MyGeneric在其他模块中应如何表现?

How would this behave for MyGeneric<CustomStringConvertible> ? MyGeneric<CustomStringConvertible>行为如何? Int is CustomStringConvertible, so Item may be an Int in a CustomStringConvertible existential. Int是CustomStringConvertible,因此Item可以是CustomStringConvertible存在中的Int。 Does this method exist? 是否存在此方法? (The obvious answer is yes, because CustomStringConvertible is not Numeric, but is that what you mean? How is that useful?) (最明显的答案是肯定的,因为CustomStringConvertible不是Numeric,但这是您的意思吗?有什么用?)

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. 在那种情况下,理想情况下,Swift会得到发展以支持它。 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. 但是,这通常表明您正在寻找的工具与您真正要解决的问题之间不匹配,因此,进一步探索它会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM