【问题标题】:Swift: Compare generic Types in generic classSwift:比较泛型类中的泛型类型
【发布时间】:2016-07-18 14:09:55
【问题描述】:

我正在快速创建一个 Matrix 类,我希望它是通用的,所以我可以像这样使用它:

let matrix: Matrix<Character>; // Or any other type

我这样创建了我的类:

class Matrix<Template>: NSObject {}

我正在创建一个将重力应用到矩阵的函数,该矩阵采用模板类型的 emptyKey,并将每个不等于 emptyKey 的元素拖到矩阵底部

// For example emptyKey is "_" and Template is String.

1 _ 2               1 _ _
3 4 5   == To ==>   3 _ 2
6 _ _               6 4 5

问题是:当我试图比较 Template 类型的特定位置的矩阵中的 value 与同样类型为 TemplateemptyKey 时,它无法编译并给了我错误:

Binary operator '==' cannot be applied to two 'Template?' operands

我正在使用 xcode 7.3.1Swift 2.2

【问题讨论】:

    标签: swift generics matrix compiler-errors operands


    【解决方案1】:

    您需要将模板约束为 Equatable。

    class Matrix<Template:Equatable> ...
    

    (另外我建议您避免使用 Optional。我不知道您在哪里使用它们,但您的错误消息表明您在哪里,它们会妨碍您。)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2012-11-16
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多