[swift-evolution] Update the signature of ObjectiveC.autoreleasepool [SR-842]

Timothy Wood tjw at omnigroup.com
Sun Mar 20 23:32:56 CDT 2016

In preparation for writing a proposal, I wanted to solicit any feedback and general level of interest on addressing SR-842, which proposes modifying ObjectiveC.autoreleasepool to allow a potentially `throw`ing body via a `rethrows` annotation. I have a branch with the very simple change applied and a test. However, Dmitri Gribenko pointed out that it would be even better if the signature was amended to allow for a generic return type:

  public func autoreleasepool<Result>(@noescape code: () throws -> Result) rethrows -> Result

It isn’t clear to me whether it is possible for a wrapper to be written that adds rethrow, since the function needs to compile under the assumption that the passed block does not throw. So, something like this doesn’t actually compile.

  func autoreleasepool_generic<ResultType>(@noescape code: Void throws -> ResultType) rethrows -> ResultType {
    // or some Result enum...
    var result:ResultType?
    var error:ErrorProtocol?

    autoreleasepool {
      do {
        result = try code()
      } catch let e {
        error = e
    if let result = result {
      return result
    // Doesn't work, since in the case that `code` doesn't throw, the whole function can't.
    throw error!

Is there a way I’m missing to write a rethrows wrapper around autoreleasepool that would provide a fair comparison?

At any rate, it seems much nicer to be able to do:

	let value = try autoreleasepool {…}

than to have a bunch of boilerplate at the call site, or for everyone to figure out how to write their own wrapper.

Some other questions for feedback that I came across while looking into this:

- Since the API is already changing, should the `code` parameter be renamed to `body`? The rest of stdlib uses `body` frequently and never uses `code` as far as I can see.
- Should the name of the generic argument be something like ‘Result’ (which might conflict with a enum that holds a value-or-error) or ‘ResultType` (which might conflict with a protocol in 2.2 land, but less so in 3.0 maybe?), or something else?



More information about the swift-evolution mailing list