Skip to content

Instantly share code, notes, and snippets.

@hborders
Last active March 13, 2017 18:45
Show Gist options
  • Save hborders/6dcd08ce0a744d3a691461ce1fd9a8d2 to your computer and use it in GitHub Desktop.
Save hborders/6dcd08ce0a744d3a691461ce1fd9a8d2 to your computer and use it in GitHub Desktop.
An Objective-C pattern for making sum types - ExampleSwitcher.m
#import "ExampleSwitcher.h" // https://gist.github.com/hborders/f378b4e0d0f1d74ff7c8149cb04c6268
@implementation ExampleSwitcher
+ (NSObject * _Nonnull)nonnullValueFrom:(Example * _Nonnull)example
switchFoo:(NSObject * _Nonnull (^ _Nonnull)(ExampleFoo * _Nonnull foo_))fooBlock
bar:(NSObject * _Nonnull (^ _Nonnull)(ExampleBar * _Nonnull bar_))barBlock {
NSParameterAssert(example);
NSParameterAssert(fooBlock);
NSParameterAssert(barBlock);
// Unfortunately, we still have this local block assignment,
// but at least it's only in one spot. All other code will
// be verified correct by the compiler.
NSObject * _Nullable __block maybeValue;
[example switchFoo:^(ExampleFoo * _Nonnull foo_) {
maybeValue = fooBlock(foo_);
}
bar:^(ExampleBar * _Nonnull bar_) {
maybeValue = barBlock(bar_);
}];
assert(maybeValue);
return (NSObject * _Nonnull) maybeValue;
}
+ (NSObject * _Nullable)nullableValueFrom:(Example * _Nonnull)example
switchFoo:(NSObject * _Nullable (^ _Nonnull)(ExampleFoo * _Nonnull foo_))fooBlock
bar:(NSObject * _Nullable (^ _Nonnull)(ExampleBar * _Nonnull bar_))barBlock {
NSParameterAssert(example);
NSParameterAssert(fooBlock);
NSParameterAssert(barBlock);
// Unfortunately, we still have this local block assignment,
// but at least it's only in one spot. All other code will
// be verified correct by the compiler.
NSObject * _Nullable __block maybeValue;
[example switchFoo:^(ExampleFoo * _Nonnull foo_) {
maybeValue = fooBlock(foo_);
}
bar:^(ExampleBar * _Nonnull bar_) {
maybeValue = barBlock(bar_);
}];
return maybeValue;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment