ios swift中相同数据类型的多变量声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32390934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:31:31  来源:igfitidea点击:

Same datatype multiple variable declaration in swift

iosxcodeswiftvariables

提问by Mutech Dev01

in objective-c we can declare variable like -NSString *a,*b,*c;

在objective-c中,我们可以像这样声明变量——NSString *a,*b,*c;

in swift there a way to declare same datatype multiple variable variable rather than doing like below

迅速有一种方法可以声明相同数据类型的多变量变量,而不是像下面那样做

var a: NSString = ""
var b: NSString = ""
var c: NSString = ""

So, is it possible to declare all a,b,c variable into one line like var (a,b,c): a:NSstring=("","","")or something?

那么,是否可以将所有 a,b,c 变量声明为一行之类的 var (a,b,c): a:NSstring=("","","")

回答by Dharmesh Kheni

You can declare multiple constants or multiple variables on a single line, separated by commas:

var a = "", b = "", c = ""

NOTE

If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

您可以在一行中声明多个常量或多个变量,用逗号分隔:

var a = "", b = "", c = ""

笔记

如果代码中存储的值不会更改,请始终使用 let 关键字将其声明为常量。变量仅用于存储需要能够更改的值。

Type Annotations:

类型注释:

You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:

var red, green, blue: Double

NOTE

It is rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference.

您可以在一行中定义多个相同类型的相关变量,以逗号分隔,并在最终变量名称后使用单个类型注释:

var red, green, blue: Double

笔记

在实践中很少需要编写类型注释。如果在定义常量或变量时为其提供初始值,Swift 几乎总能推断出要用于该常量或变量的类型,如类型安全和类型推断中所述。

Documentation HERE.

文档在这里

回答by Mutech Dev01

Swift has an odd design decision here. Placing a type on a variable affects all previous non-explicitly typed variables in a multi-line definition. Same for constants.

Swift 在这里有一个奇怪的设计决定。在变量上放置类型会影响多行定义中所有以前的非显式类型变量。常量也一样。

These two lines are equivalent (a, b and c are Double):

这两行是等价的(a、b 和 c 是 Double):

var a, b, c: Double
var a: Double, b: Double, c: Double

And these two are equivalent (a and b are Int, while c and d are Double):

这两个是等价的(a 和 b 是 Int,而 c 和 d 是 Double):

var a, b: Int, c, d: Double
var a: Int, b: Int, c: Double, d: Double