Ios 将Swift函数转换为目标C并在Swift中使用返回值

Ios 将Swift函数转换为目标C并在Swift中使用返回值,ios,objective-c,swift,Ios,Objective C,Swift,我需要在Objective-C中编写这两个Swift函数,然后在Swift中调用返回的值,我该怎么做 另外,我需要将它们放在我的AppDelegate中的什么位置 抱歉,这可能很简单,但我没有使用Objective-C的经验 提前谢谢 要转换的函数: class func getAppDelegate() -> AppDelegate { return UIApplication.shared.delegate as! AppDelegate } func getDocDir()

我需要在
Objective-C
中编写这两个
Swift
函数,然后在
Swift
中调用返回的值,我该怎么做

另外,我需要将它们放在我的
AppDelegate
中的什么位置

抱歉,这可能很简单,但我没有使用
Objective-C
的经验

提前谢谢

要转换的函数:

class func getAppDelegate() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

func getDocDir() -> String {
    return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
}
AppDelegate.m:

#import "AppDelegate.h"
#import "MainViewController.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication*)application 
 didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{

}
@end
AppDelegate.h:

#import <Cordova/CDVViewController.h>
#import <Cordova/CDVAppDelegate.h>

@interface AppDelegate : CDVAppDelegate {}


@end
#导入
#进口
@接口AppDelegate:CDVAppDelegate{}
@结束

您需要桥接标头,就这样。在桥接头文件中导入AppDelegate。桥接头文件是从objective C到Swift共享代码的接口。因此,当您向objective C项目添加任何swift文件时,它将提示您添加此头文件。e、 g.项目名称桥接头。如果没有,请检查如何手动创建

然后在此标头中导入所有需要的目标C文件,如下所示:

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import "Appdelegate.h"
然后,您可以在swift文件本身中添加您提到的函数


希望对您有所帮助……

这是您用objective-c编写的AppDelegate类,包括您的Swift方法。但我们需要知道更多的细节来提供帮助

AppDelegate.h

#import <Cordova/CDVViewController.h>
#import <Cordova/CDVAppDelegate.h>

@interface AppDelegate : CDVAppDelegate {}

+ (id)getAppDelegate;
- (NSString*)getDocDir;

@end

阿里的帖子似乎是你所问问题的正确答案:

在Objective-C中编写这两个Swift函数,然后调用 Swift中的返回值

但是,如果您的意思是只想从Swift代码调用这两个方法,为什么不在扩展中定义它呢

AppDelegate+.swift:

import UIKit

extension AppDelegate {
    class func getAppDelegate() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }

    func getDocDir() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    }

}
当然,您需要在“…-bridgeing Header.h”中导入“AppDelegate.h”


你可以像在自己的
AppDelegate

中一样使用它们,为什么你需要像这样跨入ObjC?这是一个目标C项目,我需要在我正在构建的swift文件中使用这两个值,但被告知不能有一个swift和目标CappDelegate@alimcc56但是为什么呢?然后在“函数
getAppDelegate()
是一个类方法,它返回
AppDelegate
的当前实例”中调用返回的值。如果将其设置为实例方法,则需要访问当前实例…稍微多一点,
-
+
以获取
getAppDelegate
。你说@OOPer是什么意思?。Self和[[UIApplication sharedApplication]delegate]是相同的。当您将其作为实例方法保留时,您需要使用类似于
[AnapDeleteGate getAppDelegate]
的方法,如何让
AnapDeleteGate
调用该方法?它是从
AppDelegate
类外部调用的。@哦,我明白你的意思了,更新了我的答案,谢谢。
import UIKit

extension AppDelegate {
    class func getAppDelegate() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }

    func getDocDir() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    }

}