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

前端 未结 6 1445
刺人心
刺人心 2020-12-03 04:28

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

let a = \"123\"

but the a cannot be found in

6条回答
  •  执笔经年
    2020-12-03 04:55

    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);
    

提交回复
热议问题