Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same datatype multiple variable declaration in swift

in objective-c we can declare variable like -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?

like image 558
Mutech Dev01 Avatar asked Sep 04 '15 05:09

Mutech Dev01


People also ask

How do I declare multiple variables in Swift?

You can declare multiple constants or multiple variables on a single line, separated by commas: var x = 0.0, y = 0.0, z = 0.0.

Can we do multiple declaration for same variable?

Multiple declarations of type 1 & 3 are allowed, while at most one (type 2) definition is allowed.

Can we declare multiple variable names using single data type?

You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas. If you declare more than one variable with one As clause, you cannot supply an initializer for that group of variables.

How do you declare a variable type in Swift?

Declaring VariablesThe var keyword is the only way to declare a variable in Swift. The most common and concise use of the var keyword is to declare a variable and assign a value to it. Remember that we don't end this line of code with a semicolon.


1 Answers

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.

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.

Documentation HERE.

like image 98
Dharmesh Kheni Avatar answered Oct 12 '22 07:10

Dharmesh Kheni