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

标签 swift generics

是否可以提供仅适用于泛型类型的特定实例的扩展?

例如,假设我想向 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/

相关文章:

ios - 设置 UITableView 使用的数组索引的不同方法

ios - 使用属性观察器更改 Collection View 单元格是否不好?

c# - 如何使用泛型而不是继承来拥有多个版本的东西

c# - 如何更正通用排序代码以对可空类型进行排序

通用扩展方法的 C# 特化

ios - UITextfield swift 中的 fatal error

swift - 以编程方式添加 View 和手势 - "unrecognized selector sent to instance"

swift - 使用 arc4random_uniform 返回整数和非整数 double

generics - 实现数字

java - 泛型、 super 和扩展的问题