-3

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!

JLico
  • 27
  • 1
  • 7
  • It's a negation operator so read it as "not". Personally I prefer to not use `guard` and the negation `!` in a case like this and instead write `if array.isEmpty { return }` since I find this much easier to read. – Joakim Danielson Apr 03 '22 at 18:00
  • Definitely, easier to read that way. – JLico Apr 03 '22 at 18:09

1 Answers1

0

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!

Mario Huizinga
  • 780
  • 7
  • 14