Skip to content

Instantly share code, notes, and snippets.

@OSemenovBoyarka
Created November 26, 2016 17:24
Show Gist options
  • Save OSemenovBoyarka/8f399e9ff9b354359b13b716528163be to your computer and use it in GitHub Desktop.
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
//
// 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