为什么在使用 guard 语句时需要"!"才能使用数组参数?



目前专注于结构和算法,我遇到了这个。

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
}

我问题的确切位置是警卫声明:

guard !array.isEmpty else { return false }

我不确定为什么警卫语句需要,!在!array.isEmpty中

我只需要帮助理解为什么感叹号需要放在数组参数之前。

谢谢!

该算法要求数组不为空。 !表示不。 所以!array.isEmpty意味着不为空。

guard ...的含义就像if not ...所以guard !array.isEmpty的意思是if not not array is empty,而又等价于if array.isEmpty {return false}

我看得出来,这很令人困惑!