Created
November 26, 2016 17:24
-
-
Save OSemenovBoyarka/8f399e9ff9b354359b13b716528163be to your computer and use it in GitHub Desktop.
Set of functions for safe extraction of parsed values from JSON/XML dictionaries
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
// | |
// SafeTypes.h | |
// | |
// Contains functions for safe values extraction from id types | |
// | |
// Created by Alexs on 17.11.16. | |
// | |
/** | |
* Accepts string and return string itself if it's not nil and empty string otherwise | |
*/ | |
NS_INLINE NSString *__nonnull NOT_NIL_STRING(NSString *__nullable value) { | |
return value == nil ? @"" : value; | |
} | |
/** | |
* Gets NSInteger value from NSString or NSValue type and converts it to NSNumber | |
*/ | |
NS_INLINE NSNumber *__nullable SafeNumberInt(id __nullable value) { | |
if (value == nil) | |
return nil; | |
if ([value respondsToSelector:@selector(integerValue)]) { | |
return @([value integerValue]); | |
} else { | |
NSLog(@"TYPE ERROR: Can't extract integer value from %@ in %@", value, [NSThread callStackSymbols]); | |
return nil; | |
} | |
} | |
/** | |
* Gets double value from NSString or NSValue type and converts it to NSNumber | |
*/ | |
NS_INLINE NSNumber *__nullable SafeNumberDouble(id __nullable value) { | |
if (value == nil) | |
return nil; | |
if ([value respondsToSelector:@selector(doubleValue)]) { | |
return @([value doubleValue]); | |
} else { | |
NSLog(@"TYPE ERROR: Can't extract double value from %@ in %@", value, [NSThread callStackSymbols]); | |
return nil; | |
} | |
} | |
/** | |
* Returns string value of object, using [NSString stringWithFormat:%@] | |
*/ | |
NS_INLINE NSString *__nullable SafeString(id __nullable value) { | |
return value == nil ? nil : [NSString stringWithFormat:@"%@", value]; | |
} | |
/** | |
* Returns object if it is NSDictionary or nil, if it's not a Dictionary | |
*/ | |
NS_INLINE NSDictionary *__nullable SafeDictionary(id __nullable value) { | |
if (value == nil) | |
return nil; | |
if ([value isKindOfClass:[NSDictionary class]]) { | |
return value; | |
} else { | |
NSLog(@"TYPE ERROR: Expected dictionary, but got %@ in %@", value, [NSThread callStackSymbols]); | |
return nil; | |
} | |
} | |
/** | |
* Returns object if it is NSArray or nil, if it's not an Array | |
*/ | |
NS_INLINE NSArray *__nullable SafeArray(id __nullable value) { | |
if (value == nil) | |
return nil; | |
if ([value isKindOfClass:[NSArray class]]) { | |
return value; | |
} else { | |
NSLog(@"TYPE ERROR: Expected array, but got %@ in %@", value, [NSThread callStackSymbols]); | |
return nil; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment