Swift:Variables, constants, and data types
Section 2.1: Swift: Variables, Constants, and Data Types
In this section, we'll dive into the building blocks of Swift programming: variables, constants, and data types. These concepts are fundamental to storing and manipulating data within your apps.
Variables: Storing Changeable Data
A variable is a named container that holds a value. You can think of it as a box with a label. You can put something in the box, take it out, or change its contents later.
Declaration: To create a variable, you declare it using the var keyword, followed by a name and a type.
Example:
Swift
var name: String = "Alice" // Declare a variable named "name" of type String and assign it the value "Alice"
name = "Bob" // Change the value of "name" to "Bob"
Constants: Storing Fixed Data
A constant is similar to a variable, but its value cannot be changed once it's been set. Use constants to represent values that you know won't change throughout your program's execution.
Declaration: To create a constant, you declare it using the let keyword, followed by a name and a type.
Example:
Swift
let pi: Double = 3.14159 // Declare a constant named "pi" of type Double and assign it the value 3.14159
Data Types: Classifying Data
Every value in Swift has a specific data type, which tells the compiler how to interpret and handle that value. Here are some common data types:
Int: Represents whole numbers (e.g., 5, -10, 0).
Double: Represents floating-point numbers (e.g., 3.14, -0.5).
String: Represents a sequence of characters (e.g., "Hello, world!").
Bool: Represents a Boolean value (true or false).
Type Inference: Letting Swift Figure It Out
Swift is a strongly typed language, meaning each variable or constant must have a type. However, you don't always have to explicitly specify the type when declaring a variable or constant. Swift can often infer the type based on the initial value.
Example:
Swift
var age = 25 // Swift infers that "age" is of type Int
let message = "Hi" // Swift infers that "message" is of type String
Type Annotation: Explicitly Stating the Type
In some cases, you may want to explicitly state the type of a variable or constant. This can improve code readability and catch potential errors.
Example:
Swift
var score: Int = 95
let price: Double = 19.99
Use code with caution.
content_copy
Key Takeaways
Variables (var) store values that can be changed later.
Constants (let) store values that remain fixed.
Data types classify values (e.g., Int, Double, String, Bool).
Swift can often infer the type of a variable or constant based on its initial value.
You can explicitly state the type using type annotation.
Understanding variables, constants, and data types is crucial for building any Swift program. These concepts will lay the foundation for more complex data manipulation and control flow structures that we'll explore in the upcoming sections.