Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a constant in swift that can be used in objective c

if I declare the swift constant as a global constant like:

let a = "123" 

but the a cannot be found in objective c.

How to solve this?

like image 464
user2909913 Avatar asked Jun 16 '14 05:06

user2909913


People also ask

Can you use Swift and Objective-C together?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

How do I add Objective-C to Swift?

Add any Objective-C file to your Swift project by choosing File -> New -> New File -> Objective-C File. Upon saving, Xcode will ask if you want to add a bridging header. Choose 'Yes'.


1 Answers

From Apple Doc:

You’ll have access to anything within a class or protocol that’s marked with the @objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:

  1. Generics
  2. Tuples
  3. Enumerations defined in Swift
  4. Structures defined in Swift
  5. Top-level functions defined in Swift
  6. Global variables defined in Swift
  7. Typealiases defined in Swift
  8. Swift-style variadics
  9. Nested types
  10. Curried functions

Therefore its not possible to access global variables(Constants) or global functions defined in Swift.

Possible Solutions:

  1. From the Apple Document Swift programming language, You can Declare Type Properties as

    class var constant: Int =  {     return 10 }() 

    But currently in Swift(beta-3) Type properties are not supported.

  2. You can declare a Class function to get a constant value:

    In Swift:

    class func myConst() -> String {      return "Your constant" } 

Accessing from Objective-C:

 NSString *constantValue = [ClassName myConst];  NSLog(@"%@", constantValue); 
like image 198
Yatheesha Avatar answered Oct 12 '22 13:10

Yatheesha