There are three collection types in the swift language:
Generally, a collection type is a way of grouping related items together. These collection types are sometimes referred to as data structures. An array is a data structure that is capable of storing collections of elements, of the same data types or different data types, in an ordered index.
There are basically two array types in Swift:
One dimensional array: This is a type of linear array that only uses one subscript definition to specify a particular element of the array. A subscript definition is a way of accessing the element of an array with the element indices. This can be seen as a list that can be vertically or horizontally made.
Multi-dimensional array: This is an array with two or more dimensions, and a subscript definition to specify a particular element of the array. Like tables, this can be viewed in either a vertical or horizontal arrangement. A multi-dimensional is capable of housing array of different arrays.
Arrays can be of type:
// empty array of namevar name: [String]// array of names has been assign//different names// only string is herename = ["kemi", "shayo", "Tola"]// empty array of numbersvar numbers: [Int]// array of numbers has been assign//different numbersnumbers = [3,4, 6, 7]// line comment symbol// string and integers are present herevar mixed: [Any] = [3, "james", 45]
This is a way of making modification or fetching information from the elements in an array. two slashes in the code shows comment to explain the code.
// empty array of namevar names: [String]// array of names is contain three namesnames = ["kemi", "shayo", "Tola"]// print the element in the array of namesfor element in names {print(element)}
Imagine that changes need to be mad, this is simple term will modify an element in an array.
// array of names containing//Shayo, Christopher and Mathiasvar names = ["Shayo", "Christopher", "Mathias"]// append method add new name to the list of namesnames.append("Tola")print(names)// let's remove Shayo at index 0print("This is the name remove at index 0: \(names.remove(at: 0))")
When an operation is perform in an array in this regard, the array of numbers is summed up. To see this, take a look at the code snippet below.
//array of numbers having 4, 5, 6, 7var numbers = [ 4, 5, 6, 7]// the sum of the numbers is save in a variable sum// add elements in numbers arraylet sum = numbers.reduce(0, +)// print the sumprint("the sum of numbers = \(sum)") // 22
The importance of an array in a data structure can not be over-emphasized. However, here are various methods used to solving problems in programming, some of which have been used here. I encourage you to practice other methods as well.