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

前端 未结 6 1506
刺人心
刺人心 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 05:00

    First of all you need to know about the important of auto-generated Swift header file.

    It is the one that will made the magic to transcribe the Swift code to be understandable from Objective-C.

    This file is auto-generated by Xcode (do not look for it in your project).

    The important of this file is to use the correct name, it can match with your target name, but, may not, it is the product module name. (Search for it in your project settings as "Product module")

    You need to import this file on the Objective-C class that you want to use a Swift class and also the Swift class name of your Swift file.

    #import 
    @class MySwiftClassName;
    

    My Swift class should have the prefix @objc and inherit from NSObject:

    @objc class MySwiftClassName: NSObject {
       let mySwiftVar = "123"
    }
    

    Then you can call your Swift variable from the Objective-C file:

    MySwiftClassName *mySwiftClassO = [[MySwiftClassName alloc] init];
    NSString *myVar = mySwiftClassO.mySwiftVar;
    

    Make sure to clean and rebuild your project after each change to force regenerate this auto-generated file.

    If your Swift header file was auto-generated correctly you can navigate to it by clicking over the import file name and check if all the code you need was properly transcribed.

    In the following post you can find more detailed information about this. https://solidgeargroup.com/bridging-swift-objective-c

提交回复
热议问题