Optional type for Objective-C
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 <Foundation/Foundation.h> | |
NS_ASSUME_NONNULL_BEGIN | |
@interface Optional : NSObject | |
+ (Optional*)with:(id _Nullable)value; | |
+ (Optional*)with:(id _Nullable)value as:(Class _Nonnull)valueClass; | |
- (id _Nullable)get; | |
- (id)getOrElse:(id(^)())elseBlock; | |
- (Optional*)map:(id(^)(id))mapBlock; | |
- (Optional*)flatMap:(Optional*(^)(id))flatMapBlock; | |
- (Optional*)filter:(BOOL(^)(id))filterBlock; | |
@end | |
NS_ASSUME_NONNULL_END |
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 "Optional.h" | |
@interface Optional () | |
@property (strong, nonatomic, nullable) id value; | |
@end | |
@implementation Optional | |
+ (Optional *)with:(id _Nullable)value | |
{ | |
Optional* optional = [Optional new]; | |
optional.value = value; | |
return optional; | |
} | |
+ (Optional *)with:(id)value as:(Class)valueClass | |
{ | |
if ([value isKindOfClass:valueClass]) | |
{ | |
return [Optional with:value]; | |
} | |
return [Optional with:nil]; | |
} | |
- (id)get | |
{ | |
return self.value; | |
} | |
- (id)getOrElse:(id _Nonnull (^)())elseBlock | |
{ | |
if (self.value != nil) | |
{ | |
return self.value; | |
} | |
return elseBlock(); | |
} | |
- (Optional *)map:(id _Nonnull (^)(id _Nonnull))mapBlock | |
{ | |
if (self.value != nil) | |
{ | |
return [Optional with:mapBlock(self.value)]; | |
} | |
return self; | |
} | |
- (Optional *)flatMap:(Optional* _Nonnull (^)(id _Nonnull))flatMapBlock | |
{ | |
if (self.value != nil) | |
{ | |
return flatMapBlock(self.value); | |
} | |
return self; | |
} | |
- (Optional*)filter:(BOOL (^)(id _Nonnull))filterBlock | |
{ | |
return [self flatMap:^Optional*(id value) { | |
if (filterBlock(value)) | |
{ | |
return self; | |
} | |
else | |
{ | |
return [Optional with:nil]; | |
} | |
}]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment