以下代码出现编译错误:
var a : Int = 0
var b : Int = 3
var sum : Int = 0
while (sum = a+b) < 2 {
}
错误信息是:
Cannot invoke '<' with an argument list of type '((()), IntegerLiteralConvertible)'
如何解决这个问题? (当然我可以把 sum 赋值语句放在 while 语句之外。但这不方便。还有其他建议吗?谢谢
最佳答案
在许多其他语言中,包括 C 和 Objective-C,sum = a+b
将返回 sum
的值,因此可以进行比较。
在 Swift 中,这是行不通的。这样做是为了避免常见的程序员错误。来自 The Swift Programming Language :
Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator (=) does not return a value, to prevent it from being mistakenly used when the equal to operator (==) is intended.
由于赋值运算符不返回值,因此无法与另一个值进行比较。
无法重载默认赋值运算符 (=),但您可以创建一个新运算符或重载其中一个复合运算符以添加此功能。但是,这对于您的代码的 future 读者来说是不直观的,因此您可能只想将分配移至单独的一行。
关于ios - 需要有关 Swift while 语句的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019145/