Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Forked from smileyborg/Xcode7Macros.h
Created October 13, 2015 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardopereira/285a340cec69d5ce734a to your computer and use it in GitHub Desktop.
Save ricardopereira/285a340cec69d5ce734a to your computer and use it in GitHub Desktop.
Backwards compatible macros for Objective-C nullability annotations and generics
/**
* The following preprocessor macros can be used to adopt the new nullability annotations and generics
* features available in Xcode 7, while maintaining backwards compatibility with earlier versions of
* Xcode that do not support these features.
*/
#if __has_feature(nullability)
# define __ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
# define __ASSUME_NONNULL_END NS_ASSUME_NONNULL_END
# define __NULLABLE nullable
#else
# define __ASSUME_NONNULL_BEGIN
# define __ASSUME_NONNULL_END
# define __NULLABLE
#endif
#if __has_feature(objc_generics)
# define __GENERICS(class, ...) class<__VA_ARGS__>
# define __GENERICS_TYPE(type) type
#else
# define __GENERICS(class, ...) class
# define __GENERICS_TYPE(type) id
#endif
/**
* Here are some examples of the above macros being used.
* The comments below each line represent the output of the preprocessor (e.g. what the compiler will see)
* when using both Xcode 7 and Xcode 6.
*/
#import "Xcode7Macros.h"
__ASSUME_NONNULL_BEGIN
// Xcode 7: NS_ASSUME_NONNULL_BEGIN
// Xcode 6:
@interface __GENERICS(MyClass, GenericType1, GenericType2) : NSObject
// Xcode 7: @interface MyClass<GenericType1, GenericType2> : NSObject
// Xcode 6: @interface MyClass : NSObject
@property (nonatomic, strong) __GENERICS(NSArray, __GENERICS(NSDictionary, GenericType1, GenericType2) *) *arrayOfDictionaries;
// Xcode 7: @property (nonatomic, strong) NSArray<NSDictionary<GenericType1, GenericType2> *> *arrayOfDictionaries;
// Xcode 6: @property (nonatomic, strong) NSArray *arrayOfDictionaries;
- (__NULLABLE __GENERICS_TYPE(GenericType2))someMethodWithAParameter:(__NULLABLE NSString *)param;
// Xcode 7: - (nullable GenericType2)someMethodWithAParameter:(nullable NSString *)param;
// Xcode 6: - (id)someMethodWithAParameter:(NSString *)param;
@end
__ASSUME_NONNULL_END
// Xcode 7: NS_ASSUME_NONNULL_END
// Xcode 6:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment