find the smallest number in n array in swift

You can find the smallest number in an array in Swift by using a loop to iterate through the elements of the array and keeping track of the smallest value found so far. Here's an example function that takes an array of integers as input and returns the smallest value:

main.swift
func findSmallestNumber(in numbers: [Int]) -> Int? {
    // Check if the array is empty
    guard !numbers.isEmpty else {
        return nil
    }
    
    // Set the initial smallest value to the first element of the array
    var smallest = numbers[0]
    
    // Loop through the remaining elements of the array
    for num in numbers.dropFirst() {
        // Check if the current number is smaller than the smallest seen so far
        if num < smallest {
            smallest = num
        }
    }
    return smallest
}
525 chars
19 lines

You can call this function with an array of integers like this:

main.swift
let numbers = [5, 2, 8, 1, 9]
if let smallestNumber = findSmallestNumber(in: numbers) {
    print("The smallest number in the array is \(smallestNumber)")
} else {
    print("The array is empty")
}
198 chars
7 lines

Output:

main.swift
The smallest number in the array is 1
38 chars
2 lines

gistlibby LogSnag