变量 – Swift中的多个变量赋值

如何使用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 if x = 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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...