Trending February 2024 # Learn How To Declare And Initialize An Array In Swift? # Suggested March 2024 # Top 10 Popular

You are reading the article Learn How To Declare And Initialize An Array In Swift? updated in February 2024 on the website Tai-facebook.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Learn How To Declare And Initialize An Array In Swift?

Introduction to Swift array

Swift Array is the data structure that acts as the container for storing some values of the same type in an ordered list. Swift programming language does not allow much flexibility in terms of accessing the elements and manipulation rather follows quite a strict restriction in terms of Arrays declaration and manipulation. Various operations like adding, removing, or changing values are allowed in the Swift array, but invalid values may create some intrusion which needs to be handled carefully. Assigning a constant value in Swift array might create an immutable array, and contents cannot get changed.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

Various operations can be performed over a swift array, some of them with the syntax is described below:

The syntax for Creating an Empty array containing no value with the initializer is represented as,

var sm_arr  = [sm_data] ( )

sm_data represents the empty array initialization.

The syntax for Accessing the elements from the swift array is represented as follows:

var sm_vr = Sm_Array[index]

where Sm_Array is used for representing the array, and index is used for accessing the elements.

How to declare an array in Swift?

Declaring an array in Swift is quite easy, and it then allows all the elements and values to get accessed and manipulated easily. There are two ways to declare an array which are as follows:

One way is to initialize the variable with an empty array.

Another way is to use the automatic type inference.

# To initialize the variable with an empty array:

The syntax is like the representation in the syntax section and is used accordingly.

# To use the automatic type inference.

How to initialize an array in Swift?

Initialization of array in Swift is useful for performing operations and manipulations on the elements or items present in the Swift array concerning creating, accessing, and modifying. Also, it performs all the operations on top of it. Fetching of the index and returning the index required, while traversal in the index within the range, also plays an important role.

It is initialized in the following manner:

var arr_Title = [String]()

where arr_Title is the array variable, and [String] () is the array declaration where initialization with the string will be performed.

Note: Since a dynamic array is being used as part of initialization, it must append some value.

For Example:

var arr_Title = [String]() arr_Title.append("strng_text") print(arr_Title[1]);

A very important point to keep in mind is that Array initialization in the swift language is always performed after the array declaration. Since the declaration is the first step, otherwise initialization will be incomplete.

Examples

Here are the following examples mention below

Example #1

This program demonstrates the initialization of an empty array and printing an empty array as it is not assigned any value as shown in the output.

import Foundation import Glibc let emp_Int_Arr:[Int] = [] print(emp_Int_Arr)

Output:

Example #2

This program demonstrates the usage of string array by appending and adding some of the vegetables in the array and then performed a count on top of it as shown in the output.

import Foundation import Glibc var veggies = [String]() veggies.append("Onion") veggies.append("Potato") veggies.append("Radish") print(veggies.count) print(veggies)

Output:

Example #3

This program demonstrates the string array of fruits which demonstrates the accessibility of fruits concerning the first and the last element index as shown in the output where the first index element is kiwi, and the last one is orange.

import Foundation import Glibc let fruits: [String] = ["kiwi", "apple", "orange"] print(fruits[0]) print(fruits[fruits.count - 1])

Output:

Example #4

This program demonstrates the string array in swift, which is used for displaying the usage of enumerated function as shown in the output below.

import Foundation import Glibc var cars = ["bmw", "lamborgini", "jaguar"] for (indx, val) in cars.enumerated() { print("(indx) = (val)") }

Output:

Example #5

This program demonstrates the usage of array initializer, which is used for counting the number of elements in an array with respective sizes as shown in the output below.

import Foundation import Glibc var size_1: [Int] = [8, 6, 12,18,22] size_1.append(26) print("size_1: (size_1)")

Output:

Example #6

This program demonstrates the usage of the Int array by using a for-in loop to get the unique number that is being appended in the swift array, as shown in the output below.

import Foundation import Glibc var uniq_no = [Int]() uniq_no.append(15) uniq_no.append(13) uniq_no.append(20) for uniq_no in uniq_no { print(uniq_no) }

Output:

Example #7

This program demonstrates the usage of subscript syntax to check for the accessing of elements in Swift to make the index lie with the runtime check.

import Foundation import Glibc let int_arr_0 = [20, 18, 16, 23] print(int_arr_0 [-1])

Output:

Example #8

This program demonstrates the swift array to be present in the reverse order and makes the elements represented similarly as shown in the output below as per the indexing.

Note: Basically, the array returns elements of an array in reverse order.

import Foundation import Glibc var int_ar_2 = [20,15,2,18] let revrs_arr = Array(int_ar_2.reversed()) print(revrs_arr)

Output:

Conclusion

Swift Array plays a pivotal role in a swift programming language as it allows programmers to work according to the requirement to keep the elements in place and ordered. Many operations like creation, addition, deletion, removal, and many operations can be performed on top of it for manipulating the data structure array properly.

Recommended Articles

We hope that this EDUCBA information on “Swift array” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading Learn How To Declare And Initialize An Array In Swift?

Swift Program To Sort An Array In Descending Order Using Bubble Sort

Bubble sort algorithm in swift, is the easiest search algorithm. This algorithm sorts the elements by repeatedly swapping adjacent elements if they are not present at the right place. So now we sort an array in descending order using bubble sort.

For example −

Array - [4, 7, 1, 8]

1st iteration − compare two elements, if the first element is smaller than second element then swap their position. If not, then move to next pair.

[4, 7, 1, 8] 4<7, swap the position [7, 4, 1, 8] 1<8, swap the position [7, 4, 8, 1]

2nd iteration − Again compare two elements and swap their position if first element is smaller than second element.

[7, 4, 8, 1] 4<8, swap position

3rd iteration − Again compare two elements and swap their position if first element is smaller than second element.

[7, 8, 4, 1] 7<8, swap position So the sorted array in descending order is [8, 7, 4, 1] Algorithm

Step 1 − Create a function to sort the array in descending order using bubble sort algorithm.

Step 2 − Inside the function, we run nested for-in loop to traverse over each pair of adjacent element in the given.

Step 3 − Check if array[y]<array[y+1]. If yes, then swap the position of the elements without each other. If no, then move to next pair.

Step 4 − Now outside the function create an array of integer type.

Step 5 − Call the function and pass the array into it.

Step 6 − Print the sorted array.

Example

In the following example, we will create a function named as mBubbleSort(). This function takes an array as input and sort the given array into descending order with the help of bubble sort algorithm. This function uses nested for-in loop to iterate through each pair of adjacent element the given array and swap if the first element is less than the second element. This process continue till the last unsorted element. Here the function modifies the original array with the help of inout parameter. Finally display the sorted array.

import Foundation import Glibc func mBubbleSort(_ array: inout [Int]) { let size = array.count for x in 0..<size { for y in 0..<size-x-1 { if array[y] < array[y+1] { let temp = array[y] array[y] = array[y+1] array[y+1] = temp } } } } var arr = [67, 3, 22, 89, 12, 1, 55, 80, 4] mBubbleSort(&arr) print("Sorted array in descending order: (arr)") Output Sorted array in descending order: [89, 80, 67, 55, 22, 12, 4, 3, 1] Conclusion

So this is how we can sort an array in descending order using bubble chúng tôi algorithm works well only for small set of elements, it is not suitable for larger number of elements because its average and worst case time complexity is high.

Converting Array Of Objects To An Object In Javascript

The given there is an array and the task is to convert an array of objects to an object.

Input-Output Scenario

Let’s look into an input-output scenario of converting the array objects into an object. Consider there is an array having objects in it. Now, we need to convert those array objects into a single JSON object.

Const Arr

=

[

{

1

:

'one'

}

,

{

2

:

'two'

}

]

;

Output

=

{

"1"

:

"one"

,

"2"

:

"two"

}

;

Using Object.assign()

The Object.assign() method is an in-built property in JavaScript which copies all the own enumerable properties from one or more objects to a target object.

Syntax

Following is the syntax of Object.assign(),

Object.assign(target, ...src)

where,

target is an object where the values and properties have to be copied. This target object will be returned after modification.

src is the source object containing the properties that have to be copied.

This Object.assign() method will return the target object.

Example

In the example below, we have created an array with an object in it. Then we used Object.assign() method and passed an empty object as a target object. Then by using spread(…) operator we can expand all the elements of an object as a series of values. We’ve copied the array objects into the empty object.

function

func

(

)

{

const

Cricket

=

[

{

Team

:

‘India’

}

,

{

Captain

:

‘Virat kohli’

}

,

{

Age

:

34

}

]

;

const

obj

=

Object

.

assign

(

{

}

,

Cricket

)

;

document

.

getElementById

(

“para”

)

.

innerHTML

=

JSON

.

stringify

(

obj

)

;

}

;

In the output, we have copied all the array object properties to the target object which is an empty object.

Using map() method

The map() method will create a new array by calling a function for each array element, it calls a function only once for each element in the array. The original array will not be modified.

Syntax

Following is the syntax of map() method in JavaScript.

where,

ele is the current element that is being processed in the array.

The map() method will return every element which is the result of a callback function in a new array.

Example

In the example below, we have an array of objects. In the map() method we have passed (item) as a parameter which will be processed in the array and we have passed a function to the map() method which will return the properties in the form of an array (as map() method return the output in array).

So, to convert this array of objects we use the object.assign() method. By using the spread(…) operator we extract all the elements of the output of the map() method and copied them to the target object (empty object).

const

players

=

[

{

name

:

‘Dhoni’

,

team

:

‘India’

}

,

{

name

:

‘Dilshan’

,

team

:

‘Srilanka’

}

,

{

name

:

‘Daniel sams’

,

team

:

‘Australia’

}

,

{

name

:

‘Dinesh karthik’

,

team

:

‘India’

}

]

;

function

func

(

)

{

var

obj

=

Object

.

assign

(

{

}

,

res

)

;

document

.

getElementById

(

“para”

)

.

innerHTML

=

JSON

.

stringify

(

obj

)

;

}

;

As we can see in the ouput, the array of objects has converted into an object.

Example

for loop

In this example below, we have an array of objects. We have run a for loop and iterating through the array. The loop will assign the name and team into empty object till it assigns all the properties. Then we print the empty object and will get the name – team pair as an object.

function

func

(

)

{

var

batsmen

=

[

{

name

:

‘Virat’

,

team

:

‘India’

}

,

{

name

:

‘Ponting’

,

team

:

‘Australia’

}

,

{

name

:

‘Kallis’

,

team

:

‘South Africa’

}

]

;

var

obj

=

{

}

;

let

x

=

0

;

let

len

=

batsmen

.

length

;

for

(

x

;

x

<

len

;

x

++

)

{

obj

[

batsmen

[

x

]

.

name

]

=

batsmen

[

x

]

.

team

;

}

document

.

getElementById

(

“para”

)

.

innerHTML

=

JSON

.

stringify

(

obj

)

;

}

;

In the output, we have converted the array of objects into an object with the help of for loop and an empty object.

C++ Program To Sort The Elements Of An Array In Descending Order

Arranging data items in a proper form is an essential task while solving some problems in an efficient way. The element sorting problem is one of the most commonly discussed arranging problem. In this article we will see how to arrange the array elements in descending order (decreasing order of their values) in C++.

There are many different sorting algorithms present in this domain to sort numeric or nonnumeric elements in a given order. In this article we will see only two simple methods of sorting. The bubble sort and the selection sort. Let us see them one by one with proper algorithms and C++ implementation code.

Sort array in descending order using bubble sorting technique

The bubble sorting technique is one of the most common and easier method for sorting elements in an array. This method checks two consecutive elements, if they are in correct order, then skip to the next elements, otherwise interchange them to place them in correct order. Then move towards right and do the same for the other pair of values. The bubble sorting technique has few phases, at the end of each phase, one element is being placed at the correct intended position. Let us see the algorithm for bubble sorting technique.

Algorithm

read array A and its size n as input

for i ranging from 0 to n-1, do

for j ranging from 0 to n – 2, do

if A[j] < A[j + 1], then

swap A[j] and A[j + 1]

end if

end for

end for

Example

using namespace std; void display( int arr[], int n ){ for ( int i = 0; i < n; i++ ) { cout << arr[i] << “, “; } } void swap ( int &a, int &b ){ int temp = a; a = b; b = temp; } void solve( int arr[], int n ){ int i, j; for ( i = 0; i < n; i++ ) { for ( j = 0; j < n-1; j++ ) { if ( arr[j] < arr[ j+1 ] ) { swap( arr[j], arr[ j + 1 ] ); } } } } int main(){ int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84}; int n = sizeof( arr ) / sizeof( arr[0] ); cout << “Array before sorting: “; display(arr, n); solve( arr, n ); cout << “nArray After sorting: “; display(arr, n); }

Output Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, Array After sorting: 96, 95, 89, 84, 78, 74, 63, 58, 45, 44, 36, 25, 12, 12, 10, 8, 5, 2, Sort array in descending order using selection sorting technique

In the selection sorting technique, we find either minimum element or the maximum element from the given array starting from index i to the end of this array. Assume we are finding maximum element. In each phase, it finds the minimum from index i to end, then place the element at its desired position then again search for next maximum element from the index i + 1 and so on. After completing these phases, the entire array will be sorted accordingly.

Algorithm

read array A and its size n as input

for i ranging from 0 to n-1, do

ind := index of maximum element of A starting from i to n

if A[ i ] < A[ ind ], then

swap A[ i ] and A[ ind ]

end if

end for

Example

using namespace std; void display( int arr[], int n ){ for ( int i = 0; i < n; i++ ) { cout << arr[i] << “, “; } } void swap ( int &a, int &b ){ int temp = a; a = b; b = temp; } int max_index( int arr[], int n, int s, int e ){ int max = 0, max_ind = 0; for ( int i = s; i < e; i++ ) { max = arr[i]; max_ind = i; } } return max_ind; } void solve( int arr[], int n ){ int i, j, ind; for ( i = 0; i < n; i++ ) { ind = max_index( arr, n, i, n ); if ( arr[i] < arr[ ind ] ) { swap( arr[i], arr[ ind ] ); } } } int main(){ int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12,89, 95, 63, 84}; int n = sizeof( arr ) / sizeof( arr[0] ); cout << “Array before sorting: “; display(arr, n); solve( arr, n ); cout << “nArray After sorting: “; display(arr, n); }

Output Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, Array After sorting: 96, 95, 89, 84, 78, 74, 63, 58, 45, 44, 36, 25, 12, 12, 10, 8, 5, 2, Conclusion

Sorting problem is a fundamental problem where we arrange the numbers or other values in a given arrangement logics. There are many different sorting techniques available in this domain, however, in this article we have seen two sorting techniques which are easy to implement and easy to understand. These two methods are bubble sort technique and the selection sorting technique. Using these two methods, we have sorted the set of data in descending (non-increasing) order. These two sorting methods are not much efficient in respect of time, but they are simple to understand. Both of these two methods take O(n2) amount of time, where n is the size of input. The bubble sort can be made faster by a simple checking whether when there is no swap in any phase, the next consecutive phase will not change anything.

Golang Program To Remove All Elements From An Array

In this tutorial, we will execute the program of removing all the elements of array using different set of examples. An array is a well-defined collection of elements stored at contiguous memory locations. The output is printed in the screen using fmt.Println() function. Let’s see few examples to get a clear understanding of this concept.

Syntax func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Method 1: Clear the elements in an array using nil

In this method, we will set the elements of an array equal to nil which implies that the elements will be removed from the array and an empty array will be printed on the screen using the print statement in Go language.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a function main and in the same function create an array with different values in it using append function.

Step 3 − To remove elements from the array set the array equals to nil and print the array on console.

Step 4 − Execute the print statement using fmt.Println() function where ln means the new line.

Example

Golang program to clear the elements in an array using nil

package main import "fmt" func main() { var array []int array = append(array, 2) array = append(array, 3) array = append(array, 4) array = append(array, 8) fmt.Println("The array value before setting it nil is:", array) array = nil fmt.Println("The array value after setting it nil is:") fmt.Println(array) } Output The array value before setting it nil is: [2 3 4 8] The array value after setting it nil is: [] Method 2: Clear the elements in an array using zero length

In this method, we will set the array empty slicing the array to length of zero which means that the current elements will be removed from the array and the empty array will be printed on the screen using print statement in Go language. Let’s go through the example to get the concept crystal-clear.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a function main and in the same function create an array with different values in it using append function.

Step 3 − To remove elements from the array set the array equals to slicing zero length on console.

Step 4 − Execute the print statement using fmt.Println() function where ln means the new line.

Example

Golang program to clear the elements in an array using zero length

package main import "fmt" func main() { var array []int array = append(array, 2) array = append(array, 3) array = append(array, 4) array = append(array, 8) fmt.Println("The array value before setting it to nil is:", array) array = array[:0] fmt.Println("The array value after setting it to nil is:", array) fmt.Println(array) } Output The array value before setting it to nil is: [2 3 4 8] The array value after setting it to nil is: [] [] Conclusion

We executed the program of removing elements from array using two approaches. In the very first example, we have assigned nil to the array and the array is printed empty. In the second case we used the slicing of zero length to empty array elements. Both the output displayed similar results. Hence, the program executed successfully.

C++ Program To Find The Gcds Of Given Index Ranges In An Array

In the field of data structure, a range query is a pre-processing method to operate on some input data in an efficient manner. A range query is responsible to answer any query of the particular input on any data subset. If we want to copy some data columns from a table we need to maintain an index for that particular dataset. An index is a direct link or a key, which is designed to provide an efficient searching process in a data set. It is mainly used to speed up the data retrieving from a lost data source.

In mathematics, Greatest Common Divisor aka GCD is a largest possible integer which can divide both of the integers present as the input. Here, all numbers must be present with a non-zero value. Just take an example:

GCD of 70, 80 = 10 (10 is the largest number which divides them with remainder as 0) GCD of 42, 120, 285 = 3 (3 is the largest number which divides them with remainder as 0) Algorithm to find the GCDs of given index ranges in an array (in Detailed)

Step 1 − Start

Step 2 − Construct a section of arr[0] to arr[n-1]

Step 3 − Continue the equal partition

Step 4 − Recursive call for these two parts

Step 5 − For each, save only the greatest common divisor value will save in a segment tree

Step 6 − Build another segment tree to fill it from bottom to top

Step 7 − Each node stores some data of GCD with a certain range

Step 8 − If the node range is startQuery and endQuery, then return a value node

Step 9 − Else if, the range is invalid, it will return a null or -1 as output

Step 10 − Else, return a GCD function as a recursive call

Step 11 − Terminate

Algorithm to find the GCDs of given index ranges in an array (in Short) 

Step 1 − Assume, a and b are the two non-zero integers

Step 2 − Let, a mod b = R

Step 3 − If, a=b and b=R

Step 4 − Then, repeat step 2 and step 3

Step 5 − Process will run until a mod b become greater than zero

Step 6 − GCD = b

Step 7 − Terminate

Syntax to find the GCDs of given index ranges in an array Begin if c = 0 OR d = 0, then return 0 if c = d, then return b return findGCD(c-d, d) else return findGCD(c, d-c) End

Here in this syntax we can see the possible logic code, how to find the Greatest Common Divisor of two non-zero digits. The time complexity for the process is O(Q*N*log(Ai)) and the auxiliary space is evaluated as O(1).

Approach to follow:-

Approach 1 − Program to find GCD of a number in a given Range using segment Trees

Program to find GCD of a number in a given Range using segment Trees

To find GCD of a number in a given Range using segment Trees, we need to follow some unavoidable steps.

Construction of a segment tree:

The elements of an input array are the leaf nodes.

Each individual internal node represents the GCD of all leaf nodes.

Array representation can be done by a segment tree.

-2*(i+1), index’s left element

-2*(i+2), index’s right element

-Parent is floor((i-1)/2)

Construction of a new segment tree by using the given array:

Begin the process with a segment arr[0 . . . n-1].

Divide them into two halves.

Call same for the both halves.

Store the value of GCD.

Construction of given range for GCD:

For every possible query, move the halves of thee tree present left and right.

When the given range overlaps on a half; return the node.

When it lies outside the given range, return 0 at that moment.

For partial overlapping, traverse and get return according the method follows.

Example

using namespace std; int* st; int findGcd(int ss, int se, int qs, int qe, int si) { return 0; return st[si]; int mid = ss + (se – ss) / 2; return __gcd(findGcd(ss, mid, qs, qe, si * 2 + 1), findGcd(mid + 1, se, qs, qe, si * 2 + 2)); } int findRangeGcd(int ss, int se, int arr[], int n) { cout << “Invalid Arguments” << “n”; return -1; } return findGcd(0, n – 1, ss, se, 0); } int constructST(int arr[], int ss, int se, int si) { if (ss == se) { st[si] = arr[ss]; return st[si]; } int mid = ss + (se – ss) / 2; st[si] = __gcd(constructST(arr, ss, mid, si * 2 + 1), constructST(arr, mid + 1, se, si * 2 + 2)); return st[si]; } int* constructSegmentTree(int arr[], int n) { int height = (int)(ceil(log2(n))); int size = 2 * (int)pow(2, height) – 1; st = new int[size]; constructST(arr, 0, n – 1, 0); return st; } int main() { int a[] = { 20, 30, 60, 90, 50 }; int n = sizeof(a) / sizeof(a[0]); constructSegmentTree(a, n); int l = 1; int r = 3; cout << “GCD of the given range is here. Please collect your data:”; cout << findRangeGcd(l, r, a, n) << “n”;

return 0; }

Output GCD of the given range is here. Please collect your data:30 Conclusion

In this article thus, we have developed some possible code by using the particular programming environment. With these encoded logic and the mentioned algorithm we have learned how to find out the GCDs of given index ranges in an array properly.

Update the detailed information about Learn How To Declare And Initialize An Array In Swift? on the Tai-facebook.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!