我正在尝试在 Swift 5 中执行 XOR 操作。文档似乎没有在这里明确提到使用两个布尔值进行操作:
https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html
这可能吗?它说要使用该^
操作,但尝试时出现错误:
card != nil ^ appointment.instructor == nil
错误相邻运算符位于非关联优先级组“ComparisonPrecedence”中
我正在尝试在 Swift 5 中执行 XOR 操作。文档似乎没有在这里明确提到使用两个布尔值进行操作:
https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html
这可能吗?它说要使用该^
操作,但尝试时出现错误:
card != nil ^ appointment.instructor == nil
错误相邻运算符位于非关联优先级组“ComparisonPrecedence”中
您需要定义^
for,Bool
因为它只存在于 Ints 中。请参阅此处的苹果文档。
例子:
import UIKit
import PlaygroundSupport
extension Bool {
static func ^ (left: Bool, right: Bool) -> Bool {
return left != right
}
}
let a = true
let b = false
print (a^b)
^
运算符是为整数类型定义的,但不是为Bool
. 您可以添加自己的定义,但并非绝对需要。异或运算与运算Bool
相同!=
。A XOR B
这是和的真值表A != B
:
A B A^B A!=B
F F F F
F T T T
T F T T
T T F F
所以我们可以这样写你的表达式:
(card != nil) != (appointment.instructor == nil)
不过,这有点难以理解。如果目标是确保其中一种情况是正确的,为了清楚起见,我可能会这样写:
[(card != nil), (appointment.instructor == nil)].filter({ $0 == true }).count == 1
文档明确指出这^
是按位 XOR运算符,并且由于 aBool
只是一个位,因此未在其上定义按位 XOR。如果你在表达式上加上正确的括号,你会得到正确的错误信息:
(card != nil) ^ (appointment.instructor == nil)
二元运算符“^”不能应用于两个“布尔”操作数
Swift 中没有 XOR 运算符,因此要对两个Bool
s 进行 XOR,您需要定义自己的 XOR 函数或运算符。
infix operator ^^
extension Bool {
static func ^^(lhs:Bool, rhs:Bool) -> Bool {
if (lhs && !rhs) || (!lhs && rhs) {
return true
}
return false
}
}
测试:
let trueValue:Bool? = true
let falseValue:Bool? = false
let nilValue:Bool? = nil
(trueValue != nil) ^^ (nilValue != nil) // true
(trueValue != nil) ^^ (falseValue != nil) // false
(nilValue != nil) ^^ (nilValue != nil) // false