Function Return Type

I sometimes write code like this:

func something() -> [Something: SomethingElse] {
  var result =  [Something: SomethingElse]()
  // ... stuff here
  return result
}

Wouldn't it be nice to have a Type for return values of the function? Then I could perhaps write:

func something() -> [Something: SomethingElse] {
  var result =  ReturnType()
  // ... stuff here
  return result
}

just to save some repetition, especially if the return types get more complex. (Ok could arguably use a typedef then.)

EDIT: I was just old that Delphi does it similarly but even goes a step further: https://www.oreilly.com/library/view/delphi-in-a/1565926595/re276.html

7 Likes

Please allow me to be the first to bike shed! Other Swift types, even ones dependent on where they are used don't have the word "type" in them, they rely on the leading uppercase letter, for example "Self" v. "self".

So it might be better spelled "Return", or "Result".

(and I like this, it is a small quality of life improvement...)

3 Likes

We already have precedent for accessing some of these source details in the form of #something, for example #function or #line.

To have access to this it would be more appropriate for #return or similar

1 Like

Aren't those usually strings though, for loggin purposes? Excepting #selector.

It will be very helpful in situations like this:

func makeDataSource(model: ModelType) -> RxTableViewSectionedAnimatedDataSource<Section>.ConfigureCell {
  ...
}

func resultFor(data: Data) -> Result<Result<CompletedOrder, AppError>, NetworkError> {
  let result: ReturnType
  // do stuff
}

+1

2 Likes

I don’t like it enough, because it only works at one more scope in addition to Self. It would be better to use labels, so any number of scopes could be employed. (And then Self would just become a default label.)

I’m also okay with this being implemented as a name for one scope outside, which you could then typealias for further inner scoping.

You could define a generic function to achieve something similar:

func returning<T>(_ value: T, block: (inout T) throws -> ()) rethrows -> T {
  var result = value
  try block(&result)
  return result
}

Your something function could then be written like this:

func something() -> [String: Int] {
  returning(.init()) { result in
    // ... stuff here
  }
}
1 Like
Terms of Service

Privacy Policy

Cookie Policy