Create A Variable In Swift
Code snippet for how to Create A Variable In Swift with sample and detail explanation
Swift is an intuitive programming language developed by Apple for iOS, macOS, watchOS, and beyond. In this article, we’ll learn how to create a variable in Swift, which is an essential skill to master for any Swift programmer.
Code Snippet - Create a Variable in Swift
In Swift, you define a variable with the var
keyword, followed by a suitable name for your variable, and then assign the desired value to it.
var myVar: Int = 10
In the above snippet, we created a variable named myVar
of Int
type and assigned it a value of 10
. The type annotation : Int
is declaring that myVar
can hold only integers.
Code Explanation - Create a Variable in Swift
Breaking the code, here is a step-by-step walkthrough:
-
var
: This keyword is used to declare a mutable variable in Swift. -
myVar
: This is the name of the variable. Variables in Swift can contain almost any character, including Unicode characters. However, the name of a variable cannot begin with a number, contain spaces, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. -
: Int
: By following the variable name with a colon and a type name, you specify the type of values the variable can store. TheInt
type ensures that the variable stores only integer values. -
= 10
: This statement assigns the initial value of 10 to the variable. The equals sign (=
) doesn’t imply mathematical equality but signifies assignment.
The type is inferred automatically when you provide an initial value but you may also provide it explicitly, as in our case, which is a good practice for code readability.
Remember, once you declare a variable as a particular type, you cannot declare it again with another type unless you change its value type. For instance, if your variable holds integers, you cannot suddenly start storing string values in it.
Now you can use this variable in your code, and its value will always be 10 unless you explicitly change it. Because we declared myVar
as a variable (with var
), not a constant (with let
), you can change its value as many times as you want.
myVar = 20 // myVar is now 20