Array in Swift

In Swift, an array is a collection of values that are stored in a single ordered list. For example, you could use an array to store a list of names or a list of numbers. Here is an example of how you could create an array of strings in Swift:

let names = ["Saif", "Justin", "Sarah", "Ahmed"]

In this example, names is the name of the array, and it contains four strings: “Saif”, “Justin”, “Sarah”, and “Ahmed”. The values in the array are called elements, and each element has a position in the array, known as its index. In this case, “Saif” is at index 0, “Justin” is at index 1, and so on.

You can access the elements in an array by using the array’s name followed by the index of the element you want to access in square brackets. For example, to print the first element in the names array, you could use the following code:

print(names[0]) 
// Output: "Saif"

You can also use a loop to iterate over all of the elements in an array and perform an operation on each element. Here is an example of how you could use a for loop to print all of the names in the names array:

for name in names { 
  print(name) 
} 
// Output: // Saif // Justin // Sarah // Ahmed

In addition to iterating over all the elements of an array, you can also perform various operations on arrays, such as adding or removing elements, sorting the array, and more.

Here are a few examples of common array operations in Swift:

  • To add a new element to the end of an array, use the append method:
names.append("David")
  • To insert an element at a specific index of an array, use the insert method:
names.insert("James", at: 2)
  • To remove an element from an array, use the remove method:
names.remove(at: 3)
  • To sort the elements of an array, use the sorted method:
let sortedNames = names.sorted()

Arrays are a powerful and useful data structure in Swift, and they are used in many different types of programs.


Posted

in