逻辑运算符的类型是什么? [英] What is the type of the logical operators?

查看:184
本文介绍了逻辑运算符的类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将它们用作我的 Region 结构的方法的参数:

I want to use them as a parameter to a method of my Region struct:

private func combineWith(region: RegionProtocol, combine: (Bool, Bool) -> Bool) -> Region {
    return Region() {point in
        combine(self.contains(point), region.contains(point))
    }
}

但显然,(Bool, Bool) -> Bool)不是&&或||是.如果您知道,请告诉我您的发现方式.

But apparently, (Bool, Bool) -> Bool) is not what && or || are. If you know, please let me know how you found out.

推荐答案

如果您在语句中"cmd单击""Swift"一词

If you "cmd-click" on the word "Swift" in the statement

import Swift

在Xcode中

并搜索||,您会发现它已声明为

in Xcode and search for || then you'll find that it is declared as

func ||<T : BooleanType>(lhs: T, rhs: @autoclosure () -> Bool) -> Bool

原因是||运算符的短路" 行为:如果第一个 操作数为true,则根本不能对第二个操作数求值.

The reason is the "short-circuiting" behaviour of the || operator: If the first operand is true, then the second operand must not be evaluated at all.

因此您必须将参数声明为

So you have to declare the parameter as

combine: (Bool, @autoclosure () -> Bool) -> Bool

示例:

func combineWith(a : Bool, b : Bool, combine: (Bool, @autoclosure () -> Bool) -> Bool) -> Bool {
    return combine(a, b)
}

let result = combineWith(false, true, ||)
println(result)

注意: 我使用Xcode 6.1.1对此进行了测试.自动关闭的语法 参数在Swift 1.2(Xcode 6.3)中已更改,但我还无法 将上述代码翻译为Swift 1.2(另请参见Rob的评论) 下面).

Note: I tested this with Xcode 6.1.1. The syntax for autoclosure parameters changed in Swift 1.2 (Xcode 6.3) and I haven't been able yet to translate the above code for Swift 1.2 (see also Rob's comments below).

我目前唯一能提供的东西非常丑陋 解决方法.您可以将||包装到一个没有 自动关闭参数:

The only thing that I can offer at the moment are extremely ugly workarounds. You could wrap || into a closure that does not have autoclosure parameters:

func combineWith(a : Bool, b : Bool, combine: (Bool, () -> Bool) -> Bool) -> Bool {
    return combine(a, { b })
}

let result = combineWith(false, true, { $0 || $1() } )

或者您没有短路行为:

func combineWith(a : Bool, b : Bool, combine: (Bool, Bool) -> Bool) -> Bool {
    return combine(a, b)
}

let result = combineWith(false, true, { $0 || $1 } )

这篇关于逻辑运算符的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆