简体   繁体   中英

Accessing Objective-C variables/functions from Swift

Suppose I have a connector named Connector.m (written in Objective-C). And I would like to create a new connector written using Swift, named Connector.swift. I would like to access all of the variables and methods from Swift. I have create a bridging-header and write import of the header file of the Connector. But I can't access any of global variables on the Objective-C class.

Connector.m

NSString * const kHTTP_METHOD_GET = @"GET";

Connector.swift

public class Connector: NSObject {

    var parentConnector : Connector

    override init() {
        self.parentConnector = Connector
    }

    func test() {
        print(parentConnector.kHTTP_METHOD_GET) //--> ERROR : Value of type 'Connector' has no member 'kHTTP_METHOD_GET'
    }

}

Is it possible to do this? Thanks.

Add following line in Connector.h.

extern NSString * const kHTTP_METHOD_GET;

Include Connector.h to your bridging header file.

Make sure you have header file like this...

{project-name}-Bridging-Header.h

Add your class file in Bridging-Header.h

#import "Connector.h"

And Put your below code in Connector.h file..Because in Bridging-Header.h will only import header file

NSString * const kHTTP_METHOD_GET = @"GET";

to on top of @interface scope..

我相信Connector.m中的方法/变量也需要公开才能起作用。

This sounds like a good use-case for the Adapter Pattern . But you should be able to access Objective-C code easily.

Make sure your bridging header file is named like this:

{your-project-name}-Bridging-Header.h

Inside your bridging header add the following:

#import "Connector.m"

Then you have to make sure the compiler knows about your bridging header:

Click your root project > Select your target app > Build Settings

Then scroll down until you see this:

在此处输入图片说明

Make sure your bridging header is listed, build and you should have access to your Objective-C code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM