gpt4 book ai didi

swift - Xcode 10.1 swift 4.2 运算符重载导致编译器警告 : "All paths through this function will call itself"

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:44 26 4
gpt4 key购买 nike

所以我突然收到这个编译器警告,它在 swift 3 或(我认为)swift 4.0 上不存在。下面的代码重载 += 运算符以执行向量增量:

public func += ( left:  inout CGVector, right: CGVector) {
left += right
}

并产生警告,我很困惑任何人都可以阐明为什么会发出警告以及出了什么问题吗?

最佳答案

当您执行 left += right 时,它会调用您定义的同一函数。换句话说,您的运算符重载函数 +=(左:inout CGVector,右: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 - Xcode 10.1 swift 4.2 运算符重载导致编译器警告 : "All paths through this function will call itself",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53455545/

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