在 if 语句和其他语句期间变量的感叹号前缀?

Exclamation mark prefix on variables during if statements and other as well?

即使在查看了类似的问题后,我仍然感到非常困惑,即 (!) 运算符在 if 语句、函数等中作为变量或其他对象的前缀时会做什么?

Example:  

mutating func add(value: T) 
   {  
        if !contains(items, value)
          {
          items.append(value)  
          }
   }

那里没有前缀。意思是你的 if 寻找 "items NOT containing value".

感叹号!有两个用途。当您看到它出现在对象的开头时,例如 !contains(items, values),它表示 "NOT"。例如...

let x = 10
let y = 5

if x == y {
print("x is equal to y")
} else if x != y {
print("x is NOT equal to y")
}

以上代码将打印 => "x is NOT equal to y" .

逻辑 NOT (!) 运算符可用于反转布尔值。例如...

    var falseBoolValue = false

    falseBoolValue = !falseBoolValue
    print(falseBoolValue)

上面的代码会打印=> "true"

除了用作逻辑 NOT 运算符外,感叹号还用于隐式解包可选值。每当您看到感叹号出现在对象名称的末尾时,例如在 someVariable! 中,它就被用来隐式解包一个可选值。阅读可选值以更好地理解 ! 如何与可选值一起使用。