How to create an Integer Type Array in Swift
In this tutorial, we will learn how easily we can create an Integer type Array in Swift programming. This is a very basic tutorial on creating an Int array. I have used Xcode to write my code, but you can use something else too if you wish.
So let’s start with the syntax:
Syntax to create Int Array in Swift
var myArray :[Int] = [elements]
Multiple elements can be separated by commas.
Don’t worry, we will be looking at some examples to make it easier to understand.
var myArray :[Int] = [23,34,56] print(myArray)
[23, 34, 56]
So you can see we have created an Int array and inserted some elements in it at the same time.
How to create an Int array of specific length in Swift
Here we need to focus on two things. We need to assign initial values of the elements and the size or length of the array that we are going to create.
So the syntax will be like this:
var arrayName :[Int] = Array(repeating: m, count: n)
m: This is the initial value of the elements.
n: This is the length or size of the array. In easy words, we can say this is the number of elements in that array.
Let’s see this with examples:
var newArray :[Int] = Array(repeating: 0, count: 6) print(newArray)
[0, 0, 0, 0, 0, 0]
var newArray :[Int] = Array(repeating: 9, count: 6) print(newArray)
[9, 9, 9, 9, 9, 9]
Create an Integer array without defining its size
var newArray :[Int] = Array() print(newArray)
If you need anything else apart from these, comments below I will try to resolve that too.