【问题标题】:How to make a generic class conform to a protocol for specific type?如何使泛型类符合特定类型的协议?
【发布时间】:2017-04-21 02:07:12
【问题描述】:

假设存在一个通用结构:

public struct Matrix<T> where T: FloatingPoint, T: ExpressibleByFloatLiteral {
// some methods...
}

是否可以使用where 子句扩展结构以符合受约束T 的协议?例如。像

extension Matrix where T: SpecificClass : SomeProtocol {
    // This does not compile :(
}

【问题讨论】:

    标签: swift generics swift4 generic-programming swift-protocols


    【解决方案1】:

    不,这样的构造是不可能的(至少在 Swift 3.1 左右)。

    例如:

    class SomeClass { }
    protocol SomeProtocol { }
    
    extension Matrix: SomeProtocol where T == SomeClass { }
    

    给出一个非常清晰的错误信息:

    带有约束的Matrix 类型的扩展不能有继承子句。


    但一切都没有丢失......正如亚历山大正确指出的那样,已经有一个针对 Swift 4 的提案!该功能将被称为Conditional Conformances (SE-0143)

    protocol-oriented programming 黑客的一个很好的例子:

    extension Array: Equatable where Element: Equatable {
       ...
    }
    

    如果一个数组包含相等的元素,那么该数组也是相等的。


    更新。 Swift 4 已经发布,但这个功能还没有落地。我们可能需要等到 Swift 5 才能做到这一点......

    【讨论】:

    • 这个特性叫做Conditional Conformance,已经被the Swift team in proposal 0143接受,将在Swift 4的第一阶段实现。
    • 尚未在 Swift 4 中实现 :(
    猜你喜欢
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多