无法在.m文件的Objective-C代码中调用Swift的扩展方法——找不到可见的 @interface

移动开发 2026-07-08

我有一个Objective-C类,分别带有.m和 .h文件。

我创建了一个包含一个函数的Swift文件,但尽管我在.h中声明了该函数并导入了bridging header(我想是这样),仍然无法调用它。

我的 LocatorViewController.h 文件包含:

- (void)showSearchAreaButtonIfNeeded;

我的 LocatorViewController.swift 文件包含:

@objc extension LocatorViewController {
    @objc func showSearchAreaButtonIfNeeded() { }
}

然后在 LocatorViewController.m

#import <FindUsLegacy/FindUsLegacy-Swift.h> // I can't see this file but no issues and it compiles fine. Seems like XCode auto generates this?

// Somewhere later in a function
[self showSearchAreaButtonIfNeeded];

// The above gives the error No visible @interface for 'LocatorViewController' declares the selector 'showSearchAreaButtonIfNeeded:'

在这个阶段我无法编译该项目;然而,如果我在.m中添加一个空函数

- (void)showSearchAreaButtonIfNeeded {}

现在我就能调用该函数(这很明显),项目也能编译,而且调用的是Swift版本的函数,而不是ObjC的,这让我有点惊讶——我在想是否与动态派发有关?

我原以为不需要添加那个空函数,感觉有点不对劲,所以想看看是否有更好的做法,因为其他一些问题建议在不使用空的.m定义的情况下实现,但我觉得我遵循了相同的步骤:

Swift extension "Method definition not found"

https://forums.swift.org/t/unable-to-call-swift-extension-method-from-objective-c-class/67174

Cannot call Swift method in Objective-C .m file

Swift to Objective-C header does not contain Swift classes

解决方案

这是一个可编译的Objective-C / Swift混合iOS应用的“完整”描述;你自己的实现若有差异,差异的程度就是问题所在(你可以通过搭建一个遵循本说明的小型项目来验证):

LocationViewController.h

#import <UIKit/UIKit.h>

@interface LocatorViewController : UIViewController

@end

LocationViewController.m

#import "LocatorViewController.h"
#import "FindUsLegacy-Swift.h"

@interface LocatorViewController ()

@end

@implementation LocatorViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showSearchAreaButtonIfNeeded];
}

@end

FindUsLegacy-Bridging-Header.h

#import "LocatorViewController.h"

LocatorViewController.swift

import UIKit

@objc extension LocatorViewController {
    func showSearchAreaButtonIfNeeded() { }
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章