> On 4 Oct 2017, at 14:12, Mike Kluev <mike.kl...@gmail.com> wrote:
> 
> On 4 October 2017 at 13:41, Alex Blewitt <alb...@apple.com 
> <mailto:alb...@apple.com>> wrote:
> 
> The difference between the & and && operators isn't to do with the implicit 
> conversions; it's to do with whether both sides of the expression are 
> evaluated or not.
> 
> false && system('rm -rf')
> 
> You really don't want to do that if both sides are executed ...
> 
> actually, thanks for bringing this up as it leads up to a question:
> 
> how in swift do i define my &&& operator (that i may need for whatever 
> reason, e.g. logging) that will short-circuit
> the calculation of right hand side if the left hand side is false?
> 
> infix operator &&&: LogicalConjunctionPrecedence
> 
> func &&&(left: Bool, right: Bool) -> Bool {
>       return left && right
> }
> 
> as written it doesn't short-circuit. is it possible at all in swift?

When you call the function, the arguments will be evaluated prior to the 
function body - so this won't work (as you correctly noted).

However, you can wrap the second argument in an @autoclosure, which means it 
replaces the body of the expression with a function that evaluates the 
expression automatically:

infix operator &&&: LogicalConjunctionPrecedence

func &&&(left: Bool, right: @autoclosure () -> Bool) -> Bool {
        return left && right()
}

func no() -> Bool {
  print("no")
  return false
}

func yes() -> Bool {
  print("yes")
  return true
}

print(no() &&& yes())

no
false

Alex

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to