Skip to content

Instantly share code, notes, and snippets.

@kasrak
Last active December 13, 2016 05:26
Show Gist options
  • Save kasrak/2b79c458713cf77db632 to your computer and use it in GitHub Desktop.
Save kasrak/2b79c458713cf77db632 to your computer and use it in GitHub Desktop.
Swift: combining varargs and autoclosure
// This compiles:
func immediateOr(args:Bool...) -> Bool {
for arg in args {
if arg {
return true
}
}
return false
}
// A. This doesn't compile:
func lazyOr(args: @autoclosure() -> Bool...) -> Bool {
for arg in args { // "Error: Function produces expected type '[@autoclosure() -> Bool]'"
if arg() {
return true
}
}
return false
}
// B. This doesn't compile (typealias):
typealias LazyPredicate = @autoclosure() -> Bool
func lazyOr(args: LazyPredicate...) -> Bool {
for arg in args { // "Error: Function produces expected type '[@autoclosure() -> Bool]'"
if arg() {
return true
}
}
return false
}
// C. This doesn't compile (parenthesize):
func lazyOr(args: (@autoclosure() -> Bool)...) -> Bool {
for arg in args { // "Error: Function produces expected type '[@autoclosure() -> Bool]'"
if arg() {
return true
}
}
return false
}
// D. This "works"...
func lazyOr(args: (@autoclosure() -> Bool, Int)...) -> Bool {
for arg in args {
if arg.0() {
return true
}
}
return false
}
lazyOr((expensiveA(), 42), (expensiveB(), 42))
@RenniePet
Copy link

I was excited when I saw the comment by @vivekseth, but I've now tried it and it looks like it doesn't work with Swift 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment