0

I use a Constants.h file in Objective-C that contains #define and I would like to use it in Swift 3.0. Do you think it is possible?

I have different type, for example:

/*int*/        #define EVENT_ID         12
/*Class name*/ #define FORM_TO_USE      RegistrationForm_xxxx_xxx
/*String*/    #define name             @"name1"

Any ideas?

ΩlostA
  • 2,501
  • 5
  • 27
  • 63
  • Check out this answer by me to a similar question: https://stackoverflow.com/a/46361384/433373 – Nicolas Miari Sep 22 '17 at 09:55
  • In your particular case, perhaps abandon the use of `#define` constants and use actual global variables, e.g. `int EVENT_ID = 12;` in the implementation file, and `extern int EVENT_ID;` in the header, etc. – Nicolas Miari Sep 22 '17 at 09:59
  • I checked but the thing is I would like to know if it is possible to use EVENT_ID in my example directly in Swift (as in objective-C) instead of writing 12. I would like to have a generic solution. – ΩlostA Sep 22 '17 at 10:00
  • @Claudio yes. like this #define DB_Name "test.sqlite" – Dixit Akabari Sep 22 '17 at 10:00
  • You can still use it as `EVENT_ID` everywhere. You just need to define it as **an actual variable** instead of a compile-time text-replacement rule :) – Nicolas Miari Sep 22 '17 at 10:01
  • @Nicolas MiariI understand, but that Constants.h file contains next to 10 000 #define, and if there is a solution to create a type of "bridge" ans using it directly in Swift, it should be very cool :D – ΩlostA Sep 22 '17 at 10:03
  • 1
    I'm posting an answer. Give me a second – Nicolas Miari Sep 22 '17 at 10:04
  • @Dixit Akabari But my problem is even if I put it in the Constants.h, I cannot see that in a .swift file – ΩlostA Sep 22 '17 at 10:04
  • 1
    You **can** see them if you `#include` the header file in your **Bridging Header**. – Nicolas Miari Sep 22 '17 at 10:08
  • 1
    @Claudio your Constants.h file add in "objective c bridging header" in build settings. – Dixit Akabari Sep 22 '17 at 10:10

3 Answers3

2

Best Practice for Swift Constants -

Constants.swift

struct Constants {
    static let someValue = "TEST"
    static let arrayOfTests: [String] = ["foo", "bar", someValue]
}

struct Event {
    static let id = 12
    static let name = "event Name"
}
struct NotificationKey {
    static let welcome = "event Name"
}

Use:

let eventID  = Event.id
let eventName = Event.name
let aValue = Constants.someValue
let notification = NotificationKey.welcome
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
1

In simple case we can use bridging header and import constant.h file and use EVENT_ID directly in code , this should work.

-2

Try this instead

let EVENT_ID = 12 let FORM_TO_USE = RegistrationForm_xxxx_xxx let name = name1

Muthu Mari
  • 1
  • 1
  • 3