2

I'm working on a swift project and I have made MyProjectName-Bridging-header.h In this bridge, I have added a .h file that contains multiple constants made by

#define constantName VALUE

I need to know how to use these constants into my swift file?

Tahan
  • 77
  • 2
  • 12

4 Answers4

6

Do not define constants with macros

Using macros in place of global constants or functions is a sure sign of a code smell – they're not type-safe & can make debugging a nightmare. Thankfully, Swift does away with the C preprocessor, so you can no longer use them with Swift code!

You should instead be defining constants in your Objective-C headers by using global C constants.

static NSString* const aConstString = @"foobar";
static NSInteger const aConstInteger = 42;

Or if you want to keep the values out of your headers:

extern NSString* const aConstString;
extern NSInteger const aConstInteger;

NSString* const aConstString = @"foobar";
NSInteger const aConstInteger = 42;

These will then get bridged over to a Swift global constants in your auto-generated Swift header and will look like this:

public let aConstString: String
public let aConstInteger: Int

You can now access them from your Swift code.

Hamish
  • 78,605
  • 19
  • 187
  • 280
2

You simply can't. I'd recommend using this kind of ObjC Constants.

I think the simplest/quickest solution is duplicating all your .h constant files with a .m and running a simple regex to convert your defines.

A simple set of regex would be: (does not treat escaped quotes)

Find #define

#define\s+(\w+)\s+(@".*")

Replace for .h

FOUNDATION_EXPORT NSString *const $1;

Replace for .m

NSString *const $1 = $2;

Community
  • 1
  • 1
fpg1503
  • 7,492
  • 6
  • 29
  • 49
1
make simple Constant.swift 

import UIKit

class Constant: NSObject {

    // make your constant like this get rid from macros 
    static let AppFontBold = "HelveticaNeue-Bold"
    static let AppFontRegular = "HelveticaNeue"
    static let iPhoneFontSize : CGFloat = 17
    static let iPadFontSize : CGFloat = 24

}

Note : you can invoke your constant like Constant.AppFontBold
Muhammad Noman
  • 1,566
  • 1
  • 15
  • 21
-1

Generally bridging header files are used to add objective files in swift. For constants you could make constants.swift file and add your constants using var keyword.

var constant   =          "value"

Use above constant anywhere without importing constants.swift file.

Swati Gupta
  • 354
  • 1
  • 9
  • It's not a single file, but multiple big .h files. I need to use them, not convert them to swift. – Tahan Feb 17 '16 at 12:09
  • yes, bridging headers files are used for this purpose only. But why are you adding constants in bridging header files. just import your objective-c(.h) files in that bridging header and use them(.h) in your swift files directly i.e you don't need to import those .h files again in swift files. – Swati Gupta Feb 17 '16 at 12:14