Constants and Variables
Every value in Swift is either a constant or a variable. As a Lead Engineer, you should default to using constants (let) unless you are certain the value must change during the program's execution. This 'Immutable by Default' approach reduces side effects and allows the Swift compiler to perform aggressive performance optimizations.
- let (Constant): The value is set once and cannot be changed. Similar to 'final' in Dart.
- var (Variable): The value can be updated multiple times as needed.
- Type Inference vs. Type Annotation
Swift is a Type-Safe language, but it is also smart. It uses Type Inference to automatically determine the data type based on the initial value you provide. However, you can use Type Annotation when you want to be explicit or when declaring a variable without an initial value.
- Basic Data Types
Swift provides a set of standard types for common data. Note that Swift types are capitalized (PascalCase), similar to Dart objects.
| Type | Description | Example |
|---|---|---|
| Int | Whole numbers (positive/negative) | 42 |
| Double | 64-bit floating-point numbers | 3.14159 |
| Float | 32-bit floating-point numbers | 3.14 |
| String | Textual data | "Flutter to Swift" |
| Bool | Logical true or false | true |
- String Interpolation
In Swift, you insert variables into strings using the \() syntax. This is the direct equivalent of Dart's ${} syntax.