Swift globals and global functions in objective c

前端 未结 2 617
盖世英雄少女心
盖世英雄少女心 2020-12-08 14:39

the documentation says:

Global constants defined in C and Objective-C source files are automatically imported by the Swift compiler as Swift global

相关标签:
2条回答
  • 2020-12-08 15:08

    Here is the document about it

    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:

    • Generics
    • Tuples
    • Enumerations defined in Swift
    • Structures defined in Swift
    • Top-level functions defined in Swift
    • Global variables defined in Swift
    • Typealiases defined in Swift
    • Swift-style variadics
    • Nested types
    • Curried functions

    Global variables (including constants) are unaccessible from Objective-C.

    Instead, you have to declare a class which has accessors for the global constants.

    // Swift
    public let CARDS = ["card1", "card2"]
    
    @objc class AppConstant {
       private init() {}
       class func cards() -> [String] { return CARDS }
    }
    
    // Objective-C
    NSArray *cards = [AppConstant cards];
    
    0 讨论(0)
  • 2020-12-08 15:11

    Nice answer by @rintaro, but another alternative simple Swift answer for constants that can be used in both Swift and Objective-C:

    @objcMembers
    class MyConstants: NSObject {
        static let kMyConstant1 = "ConstantValue1";
        static let kMyConstant2 = "ConstantValue2";
        static let CARDS = ["card1", "card2"]
    }
    

    You can access this on both Swift and Objective-C by:

    MyConstants.kMyConstant1 // this will return "ConstantValue1"
    MyConstants.CARDS // this will return array ["card1", "card2"]
    
    0 讨论(0)
提交回复
热议问题