Skip to content

Instantly share code, notes, and snippets.

@JensAyton
Created August 24, 2010 22:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JensAyton/548432 to your computer and use it in GitHub Desktop.
Save JensAyton/548432 to your computer and use it in GitHub Desktop.
Sketch for multiple return values in Objective-C
// Sketch for multiple return values in Objective-C
// Method declaration:
- (id, NSError *) someMethod:param;
// Desugars to:
typedef struct { id a, NSError *b } __someMethodResult; // Obviously gensym/anonymous in real implementation
- (__someMethodResult) someMethod:param;
// Return type encoding would be "{?=@@}", anonymous struct of two objects.
// Call:
id result;
NSError *error;
(result, error) = [object someMethod:param];
// Desugars to:
id result;
NSError *error;
__someMethodResult temp = [object someMethod:param];
result = temp.a;
error = temp.b;
/* The proposed syntax consists of syntactically meaningful components
in C - a comma operator in parentheses - but the statement is a
syntax error because the LHS is not an lvalue. Assigning a meaning
to otherwise invalid syntax preserves the "strict superset"
property.
*/
// Additional possibilities:
// Variable declarations in result tuple:
(id result, NSError *error) = [object someMethod:param];
// Eliding parts:
(id result, ) = [object someMethod:param];
@JensAyton
Copy link
Author

Another option would be to allow return values to be named:
- (id result, NSError *error) someMethod:param;
On the one hand, this shouldn’t add any significant complexity. On the other hand, one might say that if you need to name the return values, you’ve got something complicated enough that a real struct or object would be better.

@JensAyton
Copy link
Author

It occurs to me that there’s a great big hole in this: I didn’t address how to return multiple values from a method. In particular, this won’t work, because it has a meaning already:
- (id, NSError *) someMethod:param
{
return (param, nil);
}
I can think of three solutions offhand:

  • Add a new keyword, @return_multi or just @return, with function syntax. In the latter case, it would be an error to use regular return in multi-value methods, but OK to use @return in single-value methods and functions. Heavy-handed, ugly, generally yuck.
  • Use {braces} instead of parentheses. This reflects the underlying implementation without complicating anything, and I think it’s unambiguous.
  • Use [brackets]. This is unambiguous, but I don’t like the look. ObjC has an elegant sufficiency of brackets as it is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment