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

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

我有一个通用的 class:

class MyGeneric<Item>
{
}

我想为所有类型添加扩展方法,例如 Numeric

类似这样的东西(伪代码):

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

是否有指定此类约束的方法?

不,在 Swift 类型约束中没有办法说 "not"。

也就是说,你会用这个做什么?什么算法可以应用于不能应用于 Numeric 类型的类型类 "not Numeric"?类型类 "not Numeric" 没有可用的方法。

这个概念也是有问题的,因为类型可以在随机的地方遵守协议,而且范围小到一个文件。例如,如果一个模块在内部符合 Numeric 的类型,那么 MyGeneric 在其他模块中应该如何表现?

这对 MyGeneric<CustomStringConvertible> 有何影响? Int 是 CustomStringConvertible,因此 Item 可能是 CustomStringConvertible existential 中的 Int。这种方法存在吗? (显而易见的答案是肯定的,因为 CustomStringConvertible 不是数字,但这是你的意思吗?这有什么用?)

我想澄清的是,所有这些问题并不意味着您最初的愿望是错误的或不可能的。仔细想想,这可能是可行的,也是有用的。 And in that case, ideally, Swift would be evolved to support it. 但这通常表明您正在寻找的工具与您真正试图解决的问题不匹配,因此进一步探索这一点很有帮助。