Could such construct also allow for an if-else expression like behavior?
let result = if bool { 1 } else { 2 }
Or would this be better modeled as a non block-like expression?
let result = 1 if bool else 2
I'm just curious, this maybe be out of topic/ unrelated.
···
On Wednesday, December 9, 2015, Joe Groff via swift-evolution < swift-evolution@swift.org> wrote:
On Dec 9, 2015, at 8:47 AM, David Owens II <david@owensd.io > <javascript:_e(%7B%7D,'cvml','david@owensd.io');>> wrote:
Another language construct seems a bit much for this, right? Maybe I’m
missing something, but can’t we get the same behavior with an overload?A language construct that helps eliminate multiple other language
constructs would potentially be a net win, though. If there were closures
that supported nonlocal exits, then `do`, `for...in`, and possibly other
constructs could become library functions, and other "block-like" library
features like `autoreleasepool`, `withUnsafePointer` would work more
naturally too.-Joe
extension Array {
func forEach<U>(body: (element: Element) throws -> U?) rethrows -> U? {
for e in self {
if let result = try body(element: e) { return result }
}return nil
}
}func g(e: Int) -> Int? {
if e == 2 { return e }
return nil
}let arr = [1, 2, 3]
arr.forEach { print($0) }
let result = arr.forEach(g)
result // has the value of 2Now, Swift has some issues determining the types properly if you attempt
to inline the g function at the forEach() callsite, but that can be fixed.-David
On Dec 9, 2015, at 4:40 AM, Stephen Celis via swift-evolution < > swift-evolution@swift.org > <javascript:_e(%7B%7D,'cvml','swift-evolution@swift.org');>> wrote:
On Dec 8, 2015, at 5:13 PM, Joe Groff via swift-evolution < > swift-evolution@swift.org > <javascript:_e(%7B%7D,'cvml','swift-evolution@swift.org');>> wrote:
Another direction you might take this is to make it a type annotation on
the function type, like throws, so forEach has a type like this:func forEach(body: (Element) breaks -> ())
and a closure that `breaks` has nonlocal behavior for
break/continue/return (and is implied to be noescape and void-returning, I
guess).This is really interesting. Ruby provides similar functionality with its
lambda vs. proc, but a type annotation is much more understandable. It
could also imply @noescape automatically:func forEach(@canbreak body: Element -> Void)
Stephen
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
<javascript:_e(%7B%7D,'cvml','swift-evolution@swift.org');>
https://lists.swift.org/mailman/listinfo/swift-evolution