gpt4 book ai didi

Swift 相等函数不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:06 24 4
gpt4 key购买 nike

我想检查对象之间的相等性,但出现错误。错误在代码中。

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("...")
}

最佳答案

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

class Test {...}

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

推荐阅读:Operator Functions

关于Swift 相等函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27014880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com