find the largest element in an array in swift

You can find the largest element in an array by using the max() function in swift. Here's an example:

main.swift
let numbers = [3, 9, 2, 5, 11, 1, 7]
let largestNumber = numbers.max()

print(largestNumber) // output: Optional(11)
117 chars
5 lines

In the example above, we have an array of integers called numbers. We call the max() function on the numbers array to find the largest number. The max() function returns an optional value, so the resulting output is Optional(11).

Alternatively, you can loop through the array and compare each value to find the largest one like this:

main.swift
var maxNumber = numbers[0]

for number in numbers {
    if number > maxNumber {
        maxNumber = number
    }
}

print(maxNumber) // output: 11
147 chars
10 lines

In this example, we set the initial value of maxNumber to be the first element of the array. We then loop through each element in the array and use an if statement to compare each number with maxNumber. If a number is greater than maxNumber, we update the value of maxNumber to be that number. Finally, we print out the value of maxNumber, which is the largest element in the array.

gistlibby LogSnag