How do you declare a variable in Swift iOS?

2 min 12 sec read

Author: Manish Methani

Like human memory, Computer memory has millions of cells where it can store data or information. Now to retrieve information from those cells, each cell should be given one name called " variable name" These variables are most useful and can be of different types like integer, float, double, char, strings.

Variable Declaration in Swift

To declare variables in Swift "var" keyword is used. Semicolons are not compulsory in Swift Language. But remember if you add two statements in a single line you have to use ";" as the delimiter to separate them. Otherwise, it shows syntax error.

Syntax

var variablename = Constant Value

Example

var name = "Manish"

Let's create a sample playground , Goto File > New > Playground > Next.

Example

import UIKit
var a = 20
print(a)

Run the program in the playground.

Output

You can declare multiple variables on a single line, separated by commas:

var x = 0.0, y = 0.0, z = 0.0

Type Annotations

Annotations are used to specify the type to variables. With the help of Type Annonations, it will be clear what kind of value that specific variable can store. And this can be done by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.

Syntax

var variableName: = 

Example

var name: String
name = "Manish"

var varA,varB,varC: Float

How to use print statement in Swift?

//Playground - noun: a place where people can play

import UIKit

var name = "Manish"
var age = 23

print("(name) age is = (age)")

Output

Manish age is = 23

How was the tutorial? Nice. Right?



Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.



What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp


Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python