如何使用Swift在一行中分配多个变量?
var blah = 0 var blah2 = 2 blah = blah2 = 3 // Doesn't work???
你不是。这是一个语言功能,用于防止分配的标准不需要的副作用返回一个值,如
described in the Swift book:
Unlike the assignment operator in C and Objective-C,the assignment operator in Swift does not itself return a value. The following statement is not valid:
06000
This feature prevents the assignment operator (
=
) from being used by accident when the equal to operator (==
) is actually intended. By making ifx = y
invalid,Swift helps you to avoid these kinds of errors in your code.
所以,这有助于防止这种极其常见的错误。虽然这种错误可以在其他语言中减轻 – 例如,通过使用Yoda conditions – Swift设计师显然决定在语言层面确定你不能在脚下射击自己。但它的确意味着你不能使用:
blah = blah2 = 3
如果你绝望在一行上完成赋值,你可以使用元组语法,但你仍然必须指定每个值:
(blah,blah2) = (3,3)
…我不会推荐它。虽然一开始可能会感到不方便,但在我看来,输入整个内容是最好的方式。
blah = 3 blah2 = 3