0

将 Swift 框架导入到 Objective-C 项目时,我遇到了一个非常奇怪的问题。该项目无法构建。我收到来自 Xcode 生成的 MyFramework-Swift-h 文件的消息“预期类型”的解析问题。该警告专门针对接受类型化数组作为其单个参数的方法的签名。

快速方法如下所示:

@objc public func set(paymentMethods: [PaymentMethod]) -> ParamsBuilder {
    params.paymentMethods = paymentMethods
    return self
}

一旦编译它看起来像这样:

- (ParamsBuilder * _Nonnull)setWithPaymentMethods:(NSArray<PaymentMethod *> * _Nonnull)paymentMethods SWIFT_WARN_UNUSED_RESULT;

Parse 问题抱怨 NSArray 类型,它似乎不理解。非常奇怪的是,我发现了一个可怕的 hack 修复程序,从长远来看实际上并没有帮助。在 MyFramework-Swift-h 文件中,顶部有一个块:

#if __has_feature(modules)
@import ObjectiveC;
#endif

如果我手动添加@import UIKit,Objective C 项目现在将编译。但是,我无法弄清楚 XCode 如何确定要自动导入的内容。我的框架在很多地方都导入了 UIKit,所以它没有被导入似乎很奇怪。我也不知道为什么手动导入它有助于找到 NSArray 类型!

4

1 回答 1

0

NSArray is a Foundation collection object, not UIKit. UIKit includes Foundation via other headers (NSDataAsset.h), so you are seeing the result of NSArray being recognized.

As an example, this is from the AudioKit's header file for Swift - ObjectiveC interoperability:

//
//  AudioKit.h
//  AudioKit
//
//  Created by Aurelius Prochazka, revision history on Github.
//  Copyright © 2018 AudioKit. All rights reserved.
//
#pragma once

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#if !TARGET_OS_TV
#import <CoreAudioKit/CoreAudioKit.h>
#endif

Seems like your generated header file might have no idea what is going on as the import is missing, you need to tell it what is needed. You might have deleted the line accidentally, or the header files was generated without it. So, either

#import <Foundation/Foundation.h>

or

import Foundation

must be used to tell the header you want NS* objects defined.

Your framework can include UIKit in multiple places, yet auto-generated header might not have the methods defined in it (functions are missing @objc, etc). So, import statement might be passed out.

于 2018-06-28T18:24:53.590 回答