iosarraysswiftguard-statement

Why do I need "!" to use an array parameter while using a guard statement?


Currently focused on structures and algorithms and I came across this one.

import Foundation

let numbers = [1, 3, 56, 66, 68, 80, 99, 105, 450]

func naiveContains(_ value: Int, in array: [Int]) -> Bool {
    guard !array.isEmpty else { return false }
    let midleIndex = array.count / 2
    
    if value <= array[midleIndex] {
        for index in 0...midleIndex {
            if array[index] == value {
                return true
            }
        }
    } else {
        for index in midleIndex..<array.count {
            if array[index] == value {
                return true
            }
        }
    }
    return false
}

The exact location of my question is the guard statement:

guard !array.isEmpty else { return false }

I am not sure why the guard statement requires, ! in !array.isEmpty

I only need help in understanding why the exclamation mark needs to be placed before the array parameter.

Thank you!


Solution

  • The algorithm requires the array to be not empty. ! means not. So !array.isEmpty means is not empty.

    The meaning of guard ... is like if not ... So guard !array.isEmpty means if not not array is empty, which in turn is equivalent with if array.isEmpty {return false}

    I can see it is confusing!