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

前端 未结 6 1516
刺人心
刺人心 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:52

    Swift code:

    public class MyClass: NSObject {
        public static let myConst = "aConst"
    }
    

    and then in Objective-C:

    [MyClass myConst]
    

    Isn't this working as well? As in this works for me.

    Also this is somewhat shorter as creating a object first (alloc, init). Making a new function for every constant is... not pretty :/

    Update for Swift 4

    Because of the changes in Swift 4's Objective-C inference, you need to add the @objc annotation to the declared constant as well. The previous declaration then becomes:

    @objcMembers
    public class MyClass: NSObject {
        public static let myConst = "aConst"
    }
    

    The calling Objective-C code remains the same.

    Using @objcMembers makes all constants available (as if you'd write @objc before each constant), but I've had times where the compiler somehow wouldn't generate the corresponding ObjC code.

    In those cases I'd suggest adding the @objc decorator before the constant as well.
    I.e.: @objc public static let myConst = "aConst"

提交回复
热议问题