Use ' let ' to declare constants, and use ' var ' to declare variables.
A constant value does not need to be fetched at compile time, but you can only assign it once.
That means you can use represented to represent a value: You only have to decide once, but you need to use it many times.
var myvariable = 42
myvariable = 50
Let myconstant = 42
The types of constants or variables must be the same as the values you assign to them.
However, the declaration-time type is optional and the compiler automatically infers the type when the declaration is assigned at the same time.
In the example above, the compiler infers that ' myvariable ' is an integer because its initial value is an integer.
If the initial value does not provide enough information (or no initial value), then you need to declare the type after the variable, separated by a colon.
Let Implicitinteger = 70
Let implicitdouble = 70.0
Let explicitdouble:double = 70
Values are never implicitly converted to other types. If you need to convert a value to another type, explicitly convert it.
Let label = "the width is"
Let width = 94
Let Widthlabel = label + String (width)
There is a simpler way to convert a value to a string: write the value in parentheses, and write a backslash before the parentheses. For example:
Let apples = 3
Let oranges = 5
Let applesummary = "I has \ (apples) apples."
Let fruitsummary = "I had \ (apples + oranges) pieces of fruit."
Use square brackets ' [] ' to create arrays and dictionaries, and use subscripts or keys (key) to access the elements.
var shoppinglist = ["Catfish", "water", "tulips", "Blue paint"]
SHOPPINGLIST[1] = "Bottle of Water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
To create an empty array or dictionary, use the initialization syntax.
Let Emptyarray = [String] ()
Let emptydictionary = [String:float] ()
If the type information can be inferred, you can use ' [] ' and ' [:] ' to create an empty array and an empty dictionary-just as you would declare a variable or pass arguments to a function.
Shoppinglist = []
Occupations = [:]
Swift 001. Simple values