Skip to content

Instantly share code, notes, and snippets.

@broomburgo
Last active Sep 5, 2018
Embed
What would you like to do?
Optional type for Objective-C
#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
#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