17

In swift, Prefix.pch file is not provided. In my project, I want to declare some macros globally and use through out application.

Can anyone give me suggestion how to do it, Where to declare?

Is there any other file replaced by Prefix.pch file in swift?

VRAwesome
  • 4,721
  • 5
  • 27
  • 52
  • You cannot define macros in Swift. – Martin R Aug 04 '14 at 07:06
  • Then how to use some values through out application. for example : (1) `#define NAVIGATIONBAR_COLOR @"5B79B1"` (2) `#define ISIPAD [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad` (3) `#define PROFILE_PIC [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]` How it is possible in swift? – VRAwesome Aug 04 '14 at 07:25
  • 3
    From [Migrating Your Objective-C Code to Swift](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/Migration.html): Declare simple macros as global constants, and translate complex macros into functions (copied from this answer: http://stackoverflow.com/a/24114340/1187415) – Martin R Aug 04 '14 at 07:28
  • 1
    See http://stackoverflow.com/questions/24158648/why-isnt-projectname-prefix-pch-created-automatically-in-xcode-6 – Chris Prince Dec 26 '14 at 04:54
  • BTW -- Your NSHomeDirectory macro is bad style. It works right now, but might not in the future. Use `NSFileManager`'s `-URLForDirectory:inDomain:appropriateForURL:create:error:` for getting "special" folders like the documents folder, you shouldn't assume it is in the home directory. – uliwitness Dec 13 '22 at 10:56

1 Answers1

37

Even in Obj-C, using Macros for constants and expressions is something you shouldn't do. Taking examples from your comments:

#define NAVIGATIONBAR_COLOR @"5B79B1"

It would be better as a category method on UIColor, for example

+ (UIColor *) navigationBarColor {
    return [UIColor colorWith...];
}

The isPad macro should be either a plain function

BOOL isIPad() {
    return ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad);
}

or again a category method, e.g. on UIDevice

[UIDevice isIPad]

defined as

+ (BOOL)isIPad {
   return ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad);
}

The precompiled headers were never meant to share macros to all of your code. They were made to include framework headers there to speed up the compilation process. With the introduction of modules last year and now with the possibility to create custom modules, you don't need precompiled headers any more.

In Swift the situation is the same - there are no headers and no macros so there is also no precompiled header. Use extensions, global constants or singletons instead.

Sulthan
  • 128,090
  • 22
  • 218
  • 270