我试图在 Swift 中实现 Comparable 协议(protocol),但编译器不喜欢我重载 < 运算符的任何尝试。我检查了 Apple 文档和所有 SO 帖子,但没有一个可以编译。 Xcode 给我这个警告:
Consecutive declarations on a line must be separated by ';'
它一直建议我在小于号后插入一个分号。对我做错了什么的任何见解表示赞赏。
class SomeClass: NSObject, Equatable, Comparable{
var number: UInt32!
override init()
{
super.init()
self.number = arc4random()
}
func == (lhs: SomeClass, rhs: SomeClass) -> Bool
{
return true
}
func < (lhs: SomeClass, rhs: SomeClass) -> Bool
{
return true
}
}
最佳答案
您会看到此错误,因为必须在类定义之外重载运算符,例如移动
func == (lhs: SomeClass, rhs: SomeClass) -> Bool
{
return true
}
func < (lhs: SomeClass, rhs: SomeClass) -> Bool
{
return true
}
在您的类定义之外,它将起作用(除了它们不会通过此实现返回正确的结果)。
关于swift - 在 Swift 中重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28113207/