Constants and Variables
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
Type Annotations
It’s rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it’s defined, Swift can almost always infer the type to be used for that constant or variable
Naming Constants and Variables
Names can't begin with a number, although numbers may be included elsewhere within the name.
Printing Constants and Variables
print("The current value of friendlyWelcome is \(friendlyWelcome)")
Int
Int, which has the same size as the current platform’s native word size
Floating-Point Numbers
Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number.
Type Safety and Type Inference
- If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type.
- Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide.
Numeric Type Conversion
let pi = Double(three) + pointOneFourOneFiveNine
let integerPi = Int(pi)
Type Aliases
Type aliases define an alternative name for an existing type. You define type aliases with the typealias keyword.
typealias AudioSample = UInt16
Tuples
Tuples group multiple values into a single compound value. The values within a tuple can be of any type and don’t have to be of the same type as each other.
You can decompose a tuple’s contents into separate constants or variables, which you then access as usual:
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"
If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple:
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// Prints "The status code is 404"
Alternatively, access the individual element values in a tuple using index numbers starting at zero:
print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"
You can name the individual elements in a tuple when the tuple is defined:
let http200Status = (statusCode: 200, description: "OK")
If you name the elements in a tuple, you can use the element names to access the values of those elements:
print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200"
print("The status message is \(http200Status.description)")
// Prints "The status message is OK"
Tuples are particularly useful as the return values of functions.