Vignesh Kumar Vignesh Kumar - 1 year ago 100
Swift Question

Do you need to declare datatype of a variable in Swift?

In Swift Programming, should we need to declare datatype of the variable or will the variable change it's type based on value?

Which one is enough to declare a variable:

var MyVar: Int = 50


var Myvar = 50

Answer Source
var myVar: Int = 50


var myVar = 50

They are absolutely equivalent. The : Int is unnecessary because you are assigning 50 right there in the declaration, so Swift infers that this is to be an Int variable.

If you are going to assign as part of the declaration, the only time you need to supply the type is when the type is surprising. For example:

var myChar : Character = "s"

If you don't say Character, you'll get a String.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download