[swift-evolution] A path forward on rationalizing unicode identifiers and operators

Alex Blewitt alblue at apple.com
Wed Oct 4 08:24:01 CDT 2017


> On 4 Oct 2017, at 14:12, Mike Kluev <mike.kluev at gmail.com> wrote:
> 
> On 4 October 2017 at 13:41, Alex Blewitt <alblue at apple.com <mailto:alblue at 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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171004/59ae592c/attachment.html>


More information about the swift-evolution mailing list