Codementor Events

The “var” keyword in swift

Published Jan 08, 2018

In swift, we use the var keyword to declare a variable. Swift uses variables to store and refer to values by identifying their name. Variables must be declared before they are used.

Declaring variables

We can declare a variable in swift like below:

var friendlyWelcome = "Hello"

Notice the var keyword above, we use it to denote that FriendlyWelcome is a variable and should hold the content "Hello". We can change the value of a variable by simple changing the content

var friendlyWelcome = "Hello"
friendlyWelcome = "Ututu Oma"
// friendlyWelcome is now "Ututu Oma"

We should not use the var keyword again when we intend to change the value of the variable.

Naming variables

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.

Type annotation

We can provide a type annotationwhen declaring a variable, to be clear about the kind of values the variable can store. Below is the syntax

var variableName: <data type> = <optional initial value>

When we declare a variable without including the data type, swift automatically does that for us using the data type of the initial value. The data type can be an Integer, String, Boolean, Double, or Float. When we declare a variable as an String, Swift enforces us to only assign a content that matches the data type specified

var myName: String = "Agoi Abel"
myName = 4 //This will show an error, because the myName variable content should only be a string not an Integer (4)

Summary

It’s important that you keep the following in mind. You can declare a variable with the var keyword, and you don't need to explicitly declare the variable's type. However, remember that every variable has a type in Swift. If Swift can't infer the type, then it complains. Every variable has a type, and that type cannot be changed.

I am happy to share with this article with you. If you’ve enjoyed this article, do show support by giving a few claps 👏_ . Thanks for your time and make sure to follow me or drop your comment below_ 👇

Discover and read more posts from Abel Agoi
get started