11

I have an Objective-C class in a .h file similar to this:

@interface GlobalTags : NSObject
   extern const BOOL showMessages;
@end

and a .m file similar to this:

@implementation GlobalTags
   const BOOL showMessages = YES;
@end

In summary, what I want is to have several global variables with no need to instance a class, just to access them by importing their file. What is the best way to do this in Swift?

Thanks

EDIT: regarding getting Swift global variables from Objective-C code, it is not possible (see this post).

To make such global variables visible in Objective-C code, I'm doing this in the Swift file:

class GlobalTags: NSObject {
   static let showMessages: Bool = true;
}

Would this be the correct/best way to do?

Community
  • 1
  • 1
AppsDev
  • 11,441
  • 20
  • 81
  • 163

2 Answers2

8

it's simple. In your Constants.swift file:

let kStringConstKey : String = "YourKey"
let kBoolConstKey : Bool = true
let kIntConstKey : Int = 34
let kDoubleConstKey : Double = 25.0
Saad
  • 8,501
  • 2
  • 36
  • 49
  • There is no need to define them within a class or within another data structure? – AppsDev Apr 16 '15 at 10:14
  • no. In your Constant.swift file. Just remove the class body and simply write down these lines. Without any class or data structure. More over. Swift don't need files to import if they are developed in swift and in same project workspace. – Saad Apr 16 '15 at 10:16
  • To use any Swift file to Objective C or any Objective File to Swift. You have to use Bridging header. – Saad Apr 16 '15 at 10:22
  • Here are some example how to do that https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html http://stackoverflow.com/questions/24206732/cant-use-swift-classes-inside-objective-c – Saad Apr 16 '15 at 10:23
  • I already have the bridging header, and Swift classes are visible in my Objective-C code. However, when I remove the class body, I can't get the constants... – AppsDev Apr 16 '15 at 10:24
  • 1
    I found the response to that here: http://stackoverflow.com/questions/26960494/is-it-possible-to-access-swift-global-variables-from-an-objective-c-file – AppsDev Apr 16 '15 at 10:32
3

Make one file like File -> ios -> Swift File. It will create Empty File.

Ex.

  import Foundation
  let USER:Int = 0
  let PROMOTER:Int = 1
  let NETWORKERROR_DESC = "Network not reachable.Please check  internet connection" as String
  let NETWORKERROR_Title = "Network Unavilable" as String

Now I can access USER from anywhere in application.

Bhoomi Jagani
  • 2,353
  • 15
  • 23
  • 1
    This may be true if the project is only with swift. In case of mixture of Swift and Objective-C, you can't use this variables from Objective-C – Ankur Lahiry Feb 19 '19 at 07:29