Remove forEach?


(Michael Henson) #1

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
}