Variable declaration and assignment - Swift Tutorial
In Swift, variable declaration and assignment can be done using the var
keyword. Here's the basic syntax:
var variableName: DataType = initialValue
Let’s break down each part:
var
: It is the keyword used to declare a variable.variableName
: It is the name you choose for your variable. You can use any valid identifier name that follows Swift's naming rules.DataType
: It is the type of data the variable can hold. It can be a built-in type (e.g., Int, String, Bool) or a custom type.initialValue
: It is an optional part that allows you to assign an initial value to the variable. The assigned value must be compatible with the declared data type.
Here are a few examples:
var age: Int = 25
var name: String = "John Doe"
var isStudent: Bool = true
In the examples above, we declared three variables: age
, name
, and isStudent
. The age
variable is of type Int
and initialized with the value 25. The name
variable is of type String
and initialized with the value "John Doe". The isStudent
variable is of type Bool
and initialized with the value true
.
In Swift, type inference can also be used to automatically determine the data type of a variable based on its initial value. In such cases, you don’t need to explicitly specify the data type:
var age = 25
var name = "John Doe"
var isStudent = true
In the examples above, Swift infers the data types based on the assigned initial values. The variables age
and isStudent
are still of type Int
and Bool
, respectively, while the variable name
is of type String
.
If you’re interested in learning more about Swift, I recommend checking out my articles on Medium. You can access them through the template I created on Notion, which provides a structured learning process and easy navigation to different topics. Happy learning, and best of luck on your Swift programming journey!