Home > Enterprise >  Swift String variable
Swift String variable

Time:02-08

//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str) 

I get the same output no matter which of the two I use. What's the difference between them?

CodePudding user response:

These two are basically the same.

When you use var myVar: String = "Hello", you directly tell the swift compiler that your variable is type String.

When you use var myVar = "Hello", you do not specify the type of your variable, so the swift compiler has do do that for you.

Usually, you can get away without declaring your variable type and just have swift do it for you. However, in some cases, namely computed properties and custom classes/structures, you must declare your variable to be a specific type.

In your case, either way is fine. The end result is the same, just be aware of the difference for the future.

CodePudding user response:

These two variable are same but with different names :

var myVar 

var str

in swift Type doesn't matter that defined because, swift based on value it recognizes what type it is.

  •  Tags:  
  • Related