Swift 中的多变量赋值 [英] Multiple variable assignment in Swift

查看:60
本文介绍了Swift 中的多变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Swift 在一行中分配多个变量?

How do I assign multiple variables in one line using Swift?

    var blah = 0
    var blah2 = 2

    blah = blah2 = 3  // Doesn't work???

推荐答案

你没有.

这是一种语言功能,可防止赋值返回值的标准有害副作用,如 在 Swift 书中描述:

This is a language feature to prevent the standard unwanted side-effect of assignment returning a value, as described in the Swift book:

与 C 和 Objective-C 中的赋值运算符不同,Swift 中的赋值运算符本身不返回值.以下陈述无效:

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:

   if x = y {
       // this is not valid, because x = y does not return a value
   }

此功能可防止赋值运算符 (=) 在实际使用等号运算符 (==) 时被意外使用.通过使 if x = y 无效,Swift 可以帮助您避免代码中出现此类错误.

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 的设计者显然认为最好在语言层面确定你不能用脚射击自己.但这确实意味着您不能使用:

So, this helps prevent this extremely common error. While this kind of mistake can be mitigated for in other languages—for example, by using Yoda conditions—the Swift designers apparently decided that it was better to make certain at the language level that you couldn't shoot yourself in the foot. But it does mean that you can't use:

blah = blah2 = 3

如果您迫切希望在一行上进行赋值,则可以使用元组语法,但您仍然必须专门为每个值赋值:

If you're desperate to do the assignment on one line, you could use tuple syntax, but you'd still have to specifically assign each value:

(blah, blah2) = (3, 3)

...我不会推荐它.虽然一开始可能会觉得不方便,但在我看来,直接输入整个内容是最好的方法:

...and I wouldn't recommend it. While it may feel inconvenient at first, just typing the whole thing out is the best way to go, in my opinion:

blah = 3
blah2 = 3

这篇关于Swift 中的多变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆