Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Created May 24, 2017 06:53
Show Gist options
  • Save Tricertops/97e6c0dd9cc2c0f2f0e2ca791802eb9c to your computer and use it in GitHub Desktop.
Save Tricertops/97e6c0dd9cc2c0f2f0e2ca791802eb9c to your computer and use it in GitHub Desktop.
Macros for creating NSArray and NSSet objects as replacement for @[…] literal.
// Macros for creating NSArray and NSSet objects as replacement for @[…] literal.
let components = NSArray(street, city, state, country);
// Advantages:
// 1. Type of NSArray is inferred, in this case it’s NSArray<NSString *> *
// 2. List of objects is type-checked, so mixing types like NSArray(@42, @"Hi") will report compilation error.
// 3. Ability to allocate any class, not just NSArray. For example NSSet and NSMutableArray.
// 4. Avoids stupid clang bracket matching bug, if you know what I mean.
#define let __auto_type const
#define NSArray(first, other...) \
( (NSArray<typeof(first)> *) ({ \
typeof(first) _objects[] = {first, other}; \
NSUInteger _count = sizeof(_objects) / sizeof(id); \
[NSArray arrayWithObjects:_objects count:_count]; \
}))
#define NSSet(first, other...) \
( (NSSet<typeof(first)> *) ({ \
typeof(first) _objects[] = {first, other}; \
NSUInteger _count = sizeof(_objects) / sizeof(id); \
[NSSet setWithObjects:_objects count:_count]; \
}))
#define NSMutableArray(first, other...) \
( (NSMutableArray<typeof(first)> *) ({ \
typeof(first) _objects[] = {first, other}; \
NSUInteger _count = sizeof(_objects) / sizeof(id); \
[NSMutableArray arrayWithObjects:_objects count:_count]; \
}))
#define NSMutableSet(first, other...) \
( (NSMutableSet<typeof(first)> *) ({ \
typeof(first) _objects[] = {first, other}; \
NSUInteger _count = sizeof(_objects) / sizeof(id); \
[NSMutableSet setWithObjects:_objects count:_count]; \
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment