When Apple mentioned Swift dropped the C baggage from Objective-C they meant it.
Unfortunately there were many C tricks I used in Objective-C projects that now need a workaround. I’ve been looking at different ways to do some of the fancier things C had to give.
NSAssert in production
NSAssert is a nice way in Objective-C to throw an exception during development, but do nothing in production if the same code is run. Behind the scenes, when you compile for production all NSAssert calls are essentially stripped. In Swift you instead use assert, which will also be stripped in production.
// Objective-C NSAssert(condition == value, @"Crashing... condition is not true");
// Swift assert(condition == value, "Crashing... condition is not true")
#define during production
In Objective-C it is useful to strip certain code during production. For example, I would #define all NSLogs away when building for production, so they don’t slow down my app. So far I’ve found no Swift equivalent for this. If you know, comment below 🙂
I don’t actually recommend you use these in Objective-C anyway, but you can use #define to declare a constant in your code. Now that Swift doesn’t allow #define, you are forced to do it the proper way.
// Objective-C #define kAnimationDuration 0.3
// Swift let kAnimationDuration = 0.3
In Objective-C you can use the #pragma mark preprocessor to nicely put dividers into your selection dropdown. Right now this seems to have disappeared from Swift, however Apple engineers have said it will return in the next beta seed.
// Objective-C #pragma mark - #pragma mark View life cycle
// Swift // MARK: View life cycle
I’ve previously written about using #warning to write notes for yourself that will show up in Xcode’s native GUI. As the #pragma mark above, Apple has said this may return in the next seed.
// Objective-C #warning Clean up this code after testing
// Swift // WARNING: Clean up this code after testing
#ifdef can be used for conditionally compiling code based on a condition, such as whether it’s for iOS or Mac, or even reusing the same code on a lite and paid app and changing minor things during compilation. This exists in the exact same way in Swift, however you need to define them in a different place
// Objective-C Build settings -> Preprocessor Macros -> LITE_VERSION
// Swift Build settings -> Swift Compiler Custom Flags -> -DLITE_VERSION (yes, including the -D prefix)
// Objective-C and Swift #if LITE_VERSION // Lite version code #else // Full version code #endif