Variables and Data Types in Swift
What are Variables?
A variable is a named storage location in memory that can hold a value. In Swift, you can define a variable using the var keyword. Variables can be changed, meaning you can assign a new value to them after they have been defined.
var age = 25
This line creates a variable named age and assigns it the value of 25.
What are Data Types?
Data types specify the kind of data that can be stored in a variable. Swift is a type-safe language, meaning that every variable must have a specific data type. Some of the most common data types in Swift include:
- Int: Represents whole numbers.
- Double: Represents floating-point numbers.
- String: Represents text data.
- Bool: Represents a Boolean value (true or false).
Declaring Variables with Data Types
In Swift, you can declare a variable with a specific data type by using a colon followed by the type name. This can help prevent errors in your code.
var height: Double = 5.9
This line declares a variable named height of type Double and assigns it the value 5.9.
Type Inference
Swift also supports type inference, which means that you don't always need to specify the type of a variable. The compiler can infer the type based on the value you assign to it.
var name = "John Doe"
In this case, the compiler infers that name is of type String based on the assigned value.
Constants
In addition to variables, Swift also allows you to define constants using the let keyword. Constants cannot be changed once they have been assigned a value.
let pi = 3.14159
Here, pi is declared as a constant with a value that cannot be changed.
Summary
In this tutorial, we covered the basics of variables and data types in Swift. We learned how to declare variables, understand different data types, and the concept of constants. Understanding these concepts is crucial for effective programming in Swift.