Last active
March 13, 2017 18:45
-
-
Save hborders/6dcd08ce0a744d3a691461ce1fd9a8d2 to your computer and use it in GitHub Desktop.
An Objective-C pattern for making sum types - ExampleSwitcher.m
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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