Xcode 10.1 swift 4.2 运算符重载导致编译警告:"All paths through this function will call itself"
Xcode 10.1 swift 4.2 operator overloading causing compiler warning: "All paths through this function will call itself"
所以我突然收到 swift 3 或(我认为)swift 4.0 上不存在的编译器警告。
下面的代码重载 += 运算符以执行向量增量:
public func += ( left: inout CGVector, right: CGVector) {
left += right
}
并产生了警告,我很困惑谁能解释为什么会发出警告以及出了什么问题?
当您执行 left += right
时,它会调用您定义的同一函数。换句话说,您的运算符重载函数 += ( left: inout CGVector, right: CGVector)
将始终调用自身(无限递归)。你正在做类似
的事情
func foo(String: bar) {
foo(bar)
}
但只是将foo
替换为+=
,这是不合逻辑的。 Xcode 现在只给你一个 警告 ,它不是阻止你编译的错误。您过去可能写错了这个函数(但提醒您这是刚刚添加到编译器的警告)。
你可能想要这样的东西
public func += ( left: inout CGVector, right: CGVector) {
left = CGVector(dx: left.dx + right.dx, dy: left.dy + right.dy)
}
所以我突然收到 swift 3 或(我认为)swift 4.0 上不存在的编译器警告。 下面的代码重载 += 运算符以执行向量增量:
public func += ( left: inout CGVector, right: CGVector) {
left += right
}
并产生了警告,我很困惑谁能解释为什么会发出警告以及出了什么问题?
当您执行 left += right
时,它会调用您定义的同一函数。换句话说,您的运算符重载函数 += ( left: inout CGVector, right: CGVector)
将始终调用自身(无限递归)。你正在做类似
func foo(String: bar) {
foo(bar)
}
但只是将foo
替换为+=
,这是不合逻辑的。 Xcode 现在只给你一个 警告 ,它不是阻止你编译的错误。您过去可能写错了这个函数(但提醒您这是刚刚添加到编译器的警告)。
你可能想要这样的东西
public func += ( left: inout CGVector, right: CGVector) {
left = CGVector(dx: left.dx + right.dx, dy: left.dy + right.dy)
}