DEV Community

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

Posted on • Edited on

5

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay