what are Variable in Swift ?
Variables In Swift
We use variable in swift to store information. It is the first step of learning Ios development. Variables are the “things” in your code, like numbers, text, buttons and images. Every bit of information your app uses, is stored in a variable.
What are Variable?
Here, we will start with a simple example:-
In the above code we declared a variable named age of type Int and assigned value 24 to it and in second line we printed out value of variable with print function. Declaration is announcing new variable.
The syntax for declaring and initializing, is as follows:
- var is the keyword to start a new variable declaration
- age is the name of the variable
- : separates the variable name and type
- Int is the type of the variable (a type annotation)
- = is used to assign a value to the variable
- 24 is the value of the variable
In Swift, Variable can be changed, it's value is not constant.
- Variable Types in Swift:-
Every variable has a type. Different variable types can store different kinds of information. You can’t assign a value of one type to a variable with a different type. And once a type has been set, you can’t change it.
Here, we will see a simple example:-
This constant name has type String. You’re assigning it a value "Ram", which is a string literal. It’s the literal value of the text “Ram”. It’s called a “string”, because it’s a string of characters, or just text.
You can’t do this:
The value 99 is not a string, it’s an integer number! You can’t assign it to name, because that constant has type String. You can only assign strings to a constant with type String.
You can work with lots of basic variable types in Swift, such as:
- Int for integer numbers, i.e. whole numbers without fractions like 24
- Double for decimal numbers, i.e. numbers with fractions like 3.1415
- String for text, i.e. strings of characters like "Ragini"
- Bool for the boolean logic values true and false
In Swift, you can create variables with var. Swift can infer the type of a variable on it's own, based on the context of your code.
Here, score have type Int and 0 have type int too.
- Swift Naming Variable:-
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Swift 4 is a case-sensitive programming language.
- Swift Variable, Concatenation & Interpolation:-
In swift we can combine two variables into a single variable for that we have two ways, one is we can concatenate it and the second is to interpolate variables with parenthesis.
example of Concatenation:-
The Output of above code will be
Welcome Mumbai
- Now, we shall see example of Interpolation:-
Output will be:-
Welcome Mumbai
This is how we can define, declare and use variables in Swift Programming Language.
Comments
Post a Comment
If you have any douts, Please let me know