DEV Community

Cover image for Learn with me:Apple's Swift Variables and Constants
Ansh
Ansh

Posted on • Edited on

Learn with me:Apple's Swift Variables and Constants

Hey guys,Welcome to 2nd part of Learn With Me:Apple's Swift.In previous tutorial you learned how to write Hello World in Swift and in this tutorial we are going to learn about Variables and Constants in Swift.I will highly recommend to read the first part of Swift tutorial here.So let's get started.

Variables

In programming,variable is a storage area to store data.For eg:

var name="Swift"
Enter fullscreen mode Exit fullscreen mode

Here name is a variable storing "Swift".

Declaring Variables in Swift

In Swift,variables are declared using var keyword.
For example,

var name:String
var id:Int
Enter fullscreen mode Exit fullscreen mode

Here,
•name is a variable of type String. Meaning, it can only store textual values.
•id is a variable of Int type. Meaning, it can only store integer values.

You can assign values to a variable using = operator.

var name:String
name="Swift"
print("My favorite programming language is:",name)
Enter fullscreen mode Exit fullscreen mode

Output

My favorite programming language is:Swift
Enter fullscreen mode Exit fullscreen mode

Note:You can also assign a variable directly without the type annotation.
For example,

var name="Swift"
Enter fullscreen mode Exit fullscreen mode

Constants in Swift

A constant is a special type of variable whose value cannot be changed. A constant is declared using let keyword.For example,

let name="John Doe"
print(name)
Enter fullscreen mode Exit fullscreen mode

Output

John Doe
Enter fullscreen mode Exit fullscreen mode

If you'll try to change the value of name then you will get an error.For example,

let name="John Doe"
name="Jonathan"
print(name)
Enter fullscreen mode Exit fullscreen mode

Output

error: cannot assign to value: 'name' is a 'let' constant
Enter fullscreen mode Exit fullscreen mode

Note:You cannot declare constant without initializing it.

Conclusion

Thanks for reading.I hope it will help you a lot in achieving your dreams.And in next part we are going to learn about Literals in Swift.

Top comments (0)