Skip to content

Instantly share code, notes, and snippets.

@hborders
Created March 13, 2017 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hborders/92515b39d6a287e9cdb2331303b74fd3 to your computer and use it in GitHub Desktop.
Save hborders/92515b39d6a287e9cdb2331303b74fd3 to your computer and use it in GitHub Desktop.
An Objective-C pattern for making sum types - ExampleTestsTestTransformExample.m
#import "Example.h" // https://gist.github.com/hborders/e00d7ff965ca8f8df8f7e762a2269efb
#import "ExampleSwitcher.h" // https://gist.github.com/hborders/f378b4e0d0f1d74ff7c8149cb04c6268
#import "ExampleFoo.h" // https://gist.github.com/hborders/094f05d932b3d7a1e389184ba525b0c3
#import "ExampleBar.h" // https://gist.github.com/hborders/f1c231a89de11157adf46ee85880733a
static NSNumber * _Nonnull transformExample(Example * _Nonnull example) {
return [ExampleSwitcher<NSNumber *> nonnullValueFrom:example
switchFoo:^NSNumber * _Nonnull (ExampleFoo * _Nonnull foo_) {
return @(foo_.f.length + foo_.g.length);
}
bar:^NSNumber * _Nonnull (ExampleBar * _Nonnull bar_) {
return @(bar_.b + bar_.c);
}];
}
- (void)testTransformExample {
Example * _Nonnull fooExample = [[ExampleFoo alloc] initWithF:@"foo"
g:@"goo"];
Example * _Nonnull barExample = [[ExampleBar alloc] initWithB:2
c:3];
NSLog(@"transformed Foo: %@", transformExample(fooExample)); // transformed Foo: 6
NSLog(@"transformed Bar: %@", transformExample(barExample)); // transformed Bar: 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment