Swift等功能不起作用

时间:2014-11-19 10:46:27

标签: swift equals func

我想检查对象之间的相等但我得到一个错误。错误在代码中。

class Test {
    var key: String

    init(nameParam: String) {
        self.key = nameParam
    }


    func ==(other: Test) -> Bool {
        return other.key == self.key
    }

}

var t1 = Test(nameParam: "Test")
var t2 = Test(nameParam: "Test1")

if(t1 == t2) { // Error: 'Test' is not convertible to 'MirrorDisposition'
    println("...")
}

2 个答案:

答案 0 :(得分:3)

运算符必须在全局范围内实现,而不是在类中。所以你应该在类之外实现你的相等运算符:

class Test {...}

func == (lhs: Test, rhs: Test) -> Bool {
    return lhs.key == rhs.key
}

建议阅读:Operator Functions

答案 1 :(得分:1)

你应该这样写:

class Test : Equatable {
    var key: String

    init(nameParam: String) {
        self.key = nameParam
    }




}

func ==(lhs:Test,rhs: Test) -> Bool {
    return lhs.key == rhs.key
}

var t1 = Test(nameParam: "Test")
var t2 = Test(nameParam: "Test1")

if(t1 == t2) {
    println("...")
}