[swift-evolution] Remove forEach?

Michael Henson mikehenson at gmail.com
Sat Dec 12 19:23:05 CST 2015


Rather than starting with extra keywords, what about adding an internal
enum to the SequenceType and the forEach method signature:

protocol SequenceType {
  enum Result {
    case Break
    case Continue
  }

  ...

  func forEach(@noescape body: (Generator.Element) throws -> Result?)
rethrows

  ...
}

Then, in code:

sequence.forEach {
  x in

  if x.noMoreWork {
    return .Break
  }
  if x.notTheOneWeWant {
    return .Continue
  }

  print("Hooray, \(x)!")

  return nil
}

Given that Sequence and Generator/Iterator types are so tightly bound to
the language syntax, it might be reasonable to add some syntactic sugar on
top of this mechanism so that "break" and "continue" turn into the right
return values.

Futher, if there were also a "default return value" concept for functions,
we wouldn't even have to worry about explicitly returning nil.

func getAThingOrNot() -> Thing? = nil {
  if let thing = weCanGetAThing() {
    return thing
  }

  // implicitly returns nil
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151212/43b38cb5/attachment.html>


More information about the swift-evolution mailing list