Swift – Create Integer Variable

To create an Integer variable in Swift, declare the variable as Int, or assign any integer value to the variable, or assign new Int instance to the variable.

In the following code snippet, we declare a variable n of type Int.

var n: Int

In the following code snippet, we define a variable n and assign an integer value to the variable.

ADVERTISEMENT
var n = 0

In the following code snippet, we define a variable n and assign a new instance of Int.

var n = Int()

Let us now programmatically print the type of the variable to output, and check if the type of the variable is Int or not.

First, we will start with the process of explicit declaration of variable as Int.

main.swift

import Foundation

var n: Int
print(type(of: n))

We used type(of:) generic function to get the data type of the variable.

Output

Int

Now, assign an integer value to the variable, and check if the type of the variable is Int.

main.swift

import Foundation

var n = 0
print(type(of: n))

Output

Int

Now, we will check for new Int assignment process.

main.swift

import Foundation

var n = Int()
print(type(of: n))

Output

Int

In all the three cases, we have determined that the variable is of type Int.

Conclusion

Conclusion this Swift Tutorial, we learned how to declare or create a Int (Integer) variable in Swift, in different ways, with the help of examples.