find the smallest element in an array in swift

To find the smallest element in an array in Swift, you can use the min() method provided by the standard library. Here's an example:

main.swift
let numbers = [5, 2, 7, 1, 9, 6]
let smallest = numbers.min()

print(smallest) // Output: Optional(1)
102 chars
5 lines

In this example, we define an array of integers called numbers. We then call the min() method on the array, which returns the smallest element in the array as an optional value. We then print the value of smallest to the console.

Note that the min() method returns an optional value in case the array is empty, so you may want to use optional binding to safely unwrap the result:

main.swift
if let smallest = numbers.min() {
    print("The smallest number is \(smallest).")
} else {
    print("The array is empty.")
}
127 chars
6 lines

related categories

gistlibby LogSnag