Skip to content

Instantly share code, notes, and snippets.

@Antondomashnev
Created July 11, 2017 20:55
Show Gist options
  • Save Antondomashnev/578359441256857d58e6233a5abad535 to your computer and use it in GitHub Desktop.
Save Antondomashnev/578359441256857d58e6233a5abad535 to your computer and use it in GitHub Desktop.
Objective-C µframework - trying to imitate Result patter
NS_ASSUME_NONNULL_BEGIN
#define ResultSuccess(result) [Result<typeof(result)> succeededWithResult:result]
#define ResultFailure(error) [Result failedWithError:result]
typedef NS_ENUM(NSInteger, ResultType) {
ResultTypeSuccess,
ResultTypeFailure
};
@interface Result <__covariant ResultObjectType> : NSObject
@property (nonatomic, assign, readonly) ResultType type;
@property (nonatomic, strong, readonly, nullable) ResultObjectType result;
@property (nonatomic, strong, readonly, nullable) NSError *error;
+ (instancetype)failureWithError:(NSError *)error;
+ (instancetype)successWithResult:(ResultObjectType)result;
@end
NS_ASSUME_NONNULL_END
#import Result.h"
@interface Result ()
@property (nonatomic, assign, readwrite) ResultType type;
@property (nonatomic, strong, readwrite, nullable) id result;
@property (nonatomic, strong, readwrite, nullable) NSError *error;
@end
@implementation Result
- (instancetype)initWithType:(ResultType)type result:(id)result error:(NSError *)error {
self = [super init];
if (self) {
self.type = type;
self.result = result;
self.error = error;
}
return self;
}
#pragma mark - Interface
+ (instancetype)failedWithError:(NSError *)error {
return [[Result alloc] initWithType:ResultTypeFailure result:nil error:error];
}
+ (instancetype)successWithResult:(id)result {
return [[Result alloc] initWithType:ResultTypeSuccess result:result error:nil];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment