Use let to declare a constant and declare a variable with var. The value of a constant is not required to be known at compile time, but you must assign it a value once. This means that you can use constants to name a value and then define multiple uses at once
var myVariable = 42
myVariable = 50
let myConstant = 42
Constants or variables must have the same type as the value you assign to them. However, you do not need to always write out the type explicitly. Assigning values directly to a constant or variable allows the compiler to infer their type. For example, the following chestnut, the compiler will infer that myvariable is an integral type, because its initial value is an integer type.
If the initial value does not provide enough information (or does not provide an initial value at all), it needs to be written out behind the variable, separated by a colon
70.0
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
In swift, values are never implicitly converted to other types. If you need to convert a value to a different type, you need to declare it using the corresponding type display
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
print(widthLabel)
There is also an easier way to add a value to a string: write the value in parentheses, and then write a backslash (\) in front of the parentheses , and give a chestnut:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
Use square brackets ( []) to create arrays or dictionaries, and use square brackets to access their elements by ordinal or key
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
Use initializer syntax to create an empty array or dictionary
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
If the type information can be inferred, then you can use [] to represent an empty array, using [:] to represent an empty dictionary. For a chestnut, when you set a new value for a variable or pass a parameter to a function
shoppingList = []
occupations = [:]
swift-Basic Syntax 4