平等运算符超载未按预期工作

时间:2017-03-23 08:34:46

标签: swift operator-overloading

意识到Swift不知道如何比较数字对(作为Int的元组)。我用以下代码定义了一个类:

import Foundation

class NumberPair: NSObject {
    var row,column:Int!

    init(_ theRow: Int, _ theCol: Int) {
        row = theRow
        column = theCol
        super.init()
    }

    convenience override init() {
        self.init(0,0)
    }

    static func == (lhs: NumberPair, rhs: NumberPair) -> Bool {
        return (lhs.row == rhs.row) && (lhs.column == rhs.column)
    }

    static func != (lhs: NumberPair, rhs: NumberPair) -> Bool {
        return (lhs.row != rhs.row) || (lhs.column != rhs.column)
    }
}

然后在使用课时,我有类似的东西:

var firstArray = [NumberPair](), secondArray = [NumberPair]()
...........................
// Some code working fine that fills up firstArray and secondArray.
...........................

for pairItem in firstArray {
    if secondArray.index(of: pairItem) != nil {
        print("We found an item that is in both arrays.")
        break
    }
}

现在我的问题是这个。代码一个bove不起作用。我的意思是,虽然我确定2个数组firstArray和secondArray包含常见的数字对,但消息永远不会被打印出来。怎么了?我错过了一些明显的东西吗任何提示都将非常感激。

1 个答案:

答案 0 :(得分:1)

如果您真的想继承isEqual,请使用NSObject

    class NumberPair: NSObject {
    public var row,column:Int!

    init(_ theRow: Int, _ theCol: Int) {
        row = theRow
        column = theCol
        super.init()
    }

    override func isEqual(_ object: Any?) -> Bool {
        guard let comparingObject = object as? NumberPair else {
            return false
        }
        return row == comparingObject.row && column == comparingObject.column
    }
}

以上,或者只是从NSObject删除继承并符合Equatable协议。

class NumberPair: Equatable {
    public var row,column:Int!

    init(_ theRow: Int, _ theCol: Int) {
        row = theRow
        column = theCol
        //super.init()
    }



    static func == (lhs: NumberPair, rhs: NumberPair) -> Bool {
        return (lhs.row == rhs.row) && (lhs.column == rhs.column)
    }

    static func != (lhs: NumberPair, rhs: NumberPair) -> Bool {
        return (lhs.row != rhs.row) || (lhs.column != rhs.column)
    }
}