是否可以提供仅适用于泛型类型的特定实例的扩展?
例如,假设我想向 Int?
添加一个方法,但不向任何其他 Optional
添加方法。
这可能吗?
最佳答案
有点。由于 Optional
是一种协议(protocol),因此您可以创建扩展并对其进行约束。但是,约束不能针对类型,而必须针对协议(protocol)。
这有效:
extension Optional where Wrapped: SignedIntegerType {
func test() -> Int {
return 0
}
}
然后你就可以使用它了:
let a:Int? = nil
a.test()
但是,如果您尝试这样做:
extension Optional where Wrapped: Int {
func test() -> Int {
return 0
}
}
你会得到一个错误:
type 'Wrapped' constrained to non-protocol type 'Int'
关于swift - 在 Swift 中扩展泛型类型的具体实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666313/