斯威夫特错误:二元运算符“\u0026\u0026”不能适用于两个“布尔”操作数

前端之家收集整理的这篇文章主要介绍了斯威夫特错误:二元运算符“\u0026\u0026”不能适用于两个“布尔”操作数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
显然必须有一种方式来进行AND或OR多重布尔。

我得到这个错误,试图写一个这样的功能

func isLocationWithinView(location: CGPoint,view: UIView) {
    //        return (location.x >= CGRectGetMinX(view.frame)) && (location.x <= CGRectGetMaxX(view.frame)) && (location.y >= CGRectGetMinY(view.frame)) && (location.y <= CGRectGetMaxY(view.frame))
    var a = true
    var b = false
    return a && b // Error: Binary operator '&&' cannot be applied to two 'Bool' operands
}

这是什么解决方案?

错误是误导的:核心在于你缺少返回类型… – > Bool在你的函数签名中,因此尝试为空的元组类型()分配一个布尔值(没有明确的返回类型,函数期望返回为空的元组类型())。

您可以重现这种误导性错误,以便将布尔值分配给非布尔类型,其中布尔值是以与无效赋值相同的表达式执行逻辑AND / OR表达式的结果:

var a : () = (true && false)    /* same error */
var b : Int = (true && false)   /* same error */
var c : () = (true || false)    /* same error (for binary op. '||') */

而如果您将AND / OR操作包含在闭包中或简单地将它们分配给中间布尔变量,则会松开混淆的错误消息,并显示实际错误

var d : () = { _ -> Bool in return (true && false) }()
    /* Cannot convert call result type 'Bool' to expected type '()' */
var e = true && false
var f : () = e
    /* Cannot convert value of type 'Bool' to expected type '()' */

现在为什么你给这个误导的错误。逻辑运算符&&和||通过对其右侧表达式(rhs)进行条件评估来实现,以便只有在左手侧(lhs)评估为&& / ||的真/假的情况下,可以懒惰地评估rhs。操作符。

/* e.g. the AND '&&' logical binary infix operator */
func &&(lhs: BooleanType,@autoclosure rhs: () -> BooleanType) -> Bool {
    return lhs.boolValue ? rhs().boolValue : false
}

由于lhs本身对于后续的分配无效,可能的延迟闭包rhs会引发由Bool类型到()的“外部”无效分配引起的错误,但抛出的错误(“二进制op”和“应用…“)不是&&&呼叫。

要验证,我们可以实现我们自己的非懒惰AND运算符,如&&&

infix operator &&& {
    associativity right
    precedence 120
}
func &&&(lhs: BooleanType,rhs: BooleanType) -> Bool {
    return lhs.boolValue ? rhs.boolValue : false
}
var g : () = false &&& true
/* Cannot convert value of type 'Bool' to expected type '()' */
原文链接:https://www.f2er.com/swift/320652.html

猜你在找的Swift相关文章