Swift : Variables Declaring

 A variable provides us with named storage that our programs can manipulate. Each variable in Swift 4 has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

Swift  supports the following basic types of variables 

Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables.

Float − This is used to represent a 32-bit floating-point number. It is used to hold numbers with smaller decimal points.

Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large.

Bool − This represents a Boolean value which is either true or false.

String − This is an ordered collection of characters. For example, "Hello, World!"

Character − This is a single-character string literal. For example, "C"

Swift  also allows to define various other types of variables, which we will cover in subsequent chapters, such as Optional, Array, Dictionaries, Structures, and Classes.

The following section will cover how to declare and use various types of variables in Swift 4 programming.

[1]. Variable Declaration

A variable declaration tells the compiler where and how much to create the storage for the variable. Before you use variables, you must declare them using var keyword as follows −

var variableName = <initial value>

The following example shows how to declare a variable in Swift 


var varA = 42
print(varA)

When we run the above program using playground, we get the following result −

42 
[2]. Type Annotations

You can provide a type annotation when you declare a variable, to be clear about the kind of values the variable can store. Here is the syntax −

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

The following example shows how to declare a variable in Swift  using Annotation. Here it is important to note that if we are not using type annotation, then it becomes mandatory to provide an initial value for the variable, otherwise we can just declare our variable using type annotation.


var varA = 42
print(varA)

var varB:Float

varB = 3.14159
print(varB)

When we run the above program using playground, we get the following result −

42
3.1415901184082 
[3]. 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  is a case-sensitive programming language.

You can use simple or Unicode characters to name your variables. The following examples shows how you can name the variables −


var _var = "Hello, Swift 4!"
print(_var)

var 你好 = "你好世界"
print(你好)

When we run the above program using playground, we get the following result.

Hello, Swift 4!
你好世界 
[4]. Printing Variables

You can print the current value of a constant or variable with the print function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are valid examples −


var varA = "Godzilla"
var varB = 1000.00

print("Value of \(varA) is more than \(varB) millions")

When we run the above program using playground, we get the following result.

Value of Godzilla is more than 1000.0 millions

Swift also introduces Optionals type, which handles the absence of a value. Optionals say either "there is a value, and it equals x" or "there isn't a value at all".

An Optional is a type on its own, actually one of Swift ’s new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift .

Here’s an optional Integer declaration −

var perhapsInt: Int?

Here’s an optional String declaration −

var perhapsStr: String?

The above declaration is equivalent to explicitly initializing it to nil which means no value −

var perhapsStr: String? = nil

Let's take the following example to understand how optionals work in Swift  −


var myString:String? = nil

if myString != nil {
   print(myString)
} else {
   print("myString has nil value")
}

When we run the above program using playground, we get the following result −

myString has nil value

Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.

[5]. Forced Unwrapping

If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. This just means putting an exclamation mark at the end of the variable.

Let's take a simple example −


var myString:String?

myString = "Hello, Swift 4!"

if myString != nil {
   print(myString)
} else {
   print("myString has nil value")
}

When we run the above program using playground, we get the following result −

Optional("Hello, Swift 4!")

Now let's apply unwrapping to get the correct value of the variable −


var myString:String?

myString = "Hello, Swift 4!"

if myString != nil {
   print( myString! )
} else {
   print("myString has nil value")
}

When we run the above program using playground, we get the following result.

Hello, Swift 4! 
[6]. Automatic Unwrapping

You can declare optional variables using exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value. Let's take a simple example −


var myString:String!
myString = "Hello, Swift 4!"

if myString != nil {
   print(myString)
} else {
   print("myString has nil value")
}

When we run the above program using playground, we get the following result −

Hello, Swift 4! 
[7]. Optional Binding

Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

An optional binding for the if statement is as follows −

if let constantName = someOptional {
   statements
}

Let's take a simple example to understand the usage of optional binding −


var myString:String?
myString = "Hello, Swift 4!"

if let yourString = myString {
   print("Your string has - \(yourString)")
} else {
   print("Your string does not have a value")
}

When we run the above program using playground, we get the following result −

Your string has - Hello, Swift 4!

Swift also introduces Tuples type, which are used to group multiple values in a single compound Value.

The values in a tuple can be of any type, and do not need to be of same type.

For example, ("Tutorials Point", 123) is a tuple with two values, one of string Type, and other is integer type. It is a legal command.

let ImplementationError = (501, "Not implemented") is an error when something on the server is not implemented, It returns two values. Error Code, and Description.

You can create tuples from as many values as you want and from any number of different data types.

Here’s the syntax of Tuple declaration −

var TupleName = (Value1, value2,… any number of values)

Here’s a Tuple declaration −

var error501 = (501, “Not implemented”)

You can access the values of tuple using the index numbers that start from 0.

Here’s an example of accessing tuple Values −

print(“The code is\(error501.0)”)
print(“The definition of error is\(error501.1)”)

You can name the variables of a tuple while declaring , and you can call them using their names

var error501 = (errorCode: 501, description: “Not Implemented”)
print(error501.errorCode)   // prints 501.

Tuples are helpful in returning multiple values from a function. Like, a web application might return a tuple of type ("String", Int) to show whether the loading was successful or failed.

By returning different values in a tuple we can make decisions depending on different tuple types.

Note − Tuples are useful for temporary values and are not suited for complex data.

Constants refer to fixed values that a program may not alter during its execution. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.

Constants are treated just like regular variables except the fact that their values cannot be modified after their definition.

[8]. Constants Declaration

Before you use constants, you must declare them using let keyword as follows −

let constantName = <initial value>

Following is a simple example to show how to declare a constant in Swift  −


let constA = 42
print(constA)

When we run the above program using playground, we get the following result −

42 
[9]. Type Annotations

You can provide a type annotation when you declare a constant, to be clear about the kind of values the constant can store. Following is the syntax −

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

The following example shows how to declare a constant in Swift  using Annotation. Here it is important to note that it is mandatory to provide an initial value while creating a constant −


let constA = 42
print(constA)

let constB:Float = 3.14159
print(constB)

When we run the above program using playground, we get the following result.

42
3.1415901184082 
[10]. Naming Constants

The name of a constant 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 is a case-sensitive programming language.

You can use simple or Unicode characters to name your variables. Following are valid examples −


let _const = "Hello, Swift 4!"
print(_const)

let 你好 = "你好世界"
print(你好)

When we run the above program using playground, we get the following result −

Hello, Swift 4!
你好世界 
[11]. Printing Constants

You can print the current value of a constant or variable using print function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are valid examples −


let constA = "Godzilla"
let constB = 1000.00

print("Value of \(constA) is more than \(constB) millions")

When we run the above program using playground, we get the following result −

Value of Godzilla is more than 1000.0 millions


Comments

Popular posts from this blog

Java : Variables Declaring

Install DNF in RHEL/CentOS 7

SQL Self JOIN