How do type inference and type annotations work in Swift?

Type inference and type annotations are fundamental features in Swift that allow developers to define the types of variables and constants in a flexible and efficient way.

Type Inference

Type inference allows Swift to automatically deduce the type of a variable or constant based on the value assigned to it. This means that you don’t need to explicitly specify the type, and Swift can figure it out for you.

Type Annotations

Type annotations, on the other hand, are used when you want to specify the type of a variable or constant explicitly. This can be useful for clarity, especially when the inferred type may not be obvious.

Examples:

// Type inference let inferredInteger = 42 // Swift infers this as Int let inferredDouble = 3.14159 // Swift infers this as Double // Type annotation let annotatedInteger: Int = 7 let annotatedDouble: Double = 2.71828

Swift type inference type annotations programming Swift language