Swift Fundamentals : Constants and Variables

March 2016
Uncategorized

In Swift there are two ways of storing data, one is using variables and the other is constants.

Variables

Swift Variables can be modified after you assign an initial value, but you can not change their type. The reason being, the variables are mutable. When you declare a variable they can infer the variable type.
For example:

Swift

1

varcar=“vw”

the variable car is infered to be a string. Because the car is mutable the value can change:

Swift

1

car=“bmw”

After variables are defined you can not change their type:

Swift

1

car=2016// it would give an error

Constants

Swift Constants are inmutable and they infer their type when you initialize the constant. For example:

Swift

1

letyear=2016

year is inferred to be Int., year can not be modified either in the value or the type.

Static Typing and Type Inference

When you create a variable or a constant they can be a strong type or use type inference to determine the initial type.

Statically Typed

Being statically typed means that all your variables and constants MUST have their types declared in advance. Once you have declare (inferred) your variables and constants type cannot be change.

Swift

1

2

varbook:String

book="Swift book"

Type Inference / Strongly Typed

You can explicitly declare the type of your variable/constant but you don’t need to do this in Swift, it will infer the type if you assign the initial value. For example this is how you explicitly declare its type:

1

2

varmessage:String

message=“greetings”

Another way of doing it would be

1

varmessage:String=“greetings”

Please let me know if you have any questions by leaving a comment below or on twitter @luisemedr