简体   繁体   English

在Swift中扩展泛型类型的具体实例

[英]extend a concrete instance of a generic type in Swift

Is it possible to provide an extension that only applies to a specific instance of a generic type? 是否可以提供仅适用于泛型类型的特定实例的扩展?

For example, say I want to add a method to Int? 例如,假设我要向Int?添加方法Int? , but not to any other Optional . ,但不包括其他任何Optional

Is this possible? 这可能吗?

Kind of. 的种类。 Since Optional is a protocol, you can create an extension and constrain it. 由于Optional是协议,因此您可以创建扩展并对其进行约束。 However, the constraint can't be on a type, but needs to be on a protocol. 但是,约束不能在类型上,而必须在协议上。

This works: 这有效:

extension Optional where Wrapped: SignedIntegerType {
    func test() -> Int {
        return 0
    }
}

and then you can use it: 然后您可以使用它:

let a:Int? = nil
a.test()

However, if you try to do: 但是,如果您尝试这样做:

extension Optional where Wrapped: Int {
    func test() -> Int {
        return 0
    }
}

you'll get an error: 你会得到一个错误:

type 'Wrapped' constrained to non-protocol type 'Int' 类型'Wrapped'限制为非协议类型'Int'

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

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