加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:59:40 所属栏目:百科 来源:网络整理
导读:如何使用Swift在一行中分配多个变量? var blah = 0 var blah2 = 2 blah = blah2 = 3 // Doesn't work??? 你不是。这是一个语言功能,用于防止分配的标准不需要的副作用返回一个值,如 described in the Swift book: Unlike the assignment operator in C a
如何使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读