简体   繁体   中英

Objective C to Swift interoperability issues

I have a curious case where I have the following Objective C protocol:

NS_ASSUME_NONNULL_BEGIN
@protocol AccountCriteria <NSObject>
- (BOOL)criteriaIsApplicableForIdentifier:(NSString *)identifier;
- (nullable id <ModularFactory>)criteriaMetForAccount:(Account *)account error:(NSError **)error NS_SWIFT_NOTHROW;
@end
NS_ASSUME_NONNULL_END

To which I have decided to have a Swift class implement the protocol, like so:

import Foundation

@objc(PaymentCriteria)
public class PaymentCriteria: NSObject, AccountCriteria {

    public func criteriaIsApplicable(forIdentifier identifier: String) -> Bool {
        //Lots of code here
    }

    public func criteriaMet(for account: Account, error: NSErrorPointer) -> ModularFactory? {

        //Lots of code here
    }

}

The intention is to use the PaymentCriteria class in other Objective C code. However with this particular code I keep getting a Lexical or Preprocessor Issue . Now if I remove the public from the class everything builds fine. However, I can't use PaymentCriteria in any Objective C code.

If I keep the class as public but remove AccountCriteria from the class, everything still builds fine. However, I have to have this class abide by the protocol. So this route doesn't help me very much as well.

So my question is, why can't I have a Swift class abide by an Objective C protocol and then try and use that Swift class in Objective C? Or is there something pernicious that I'm doing wrong in the Swift class?

As I understood, the issue here with let's call it, cyclic importing .

So, You've created Objc protocol, then add this Objc file to Bridging header. It is being imported to all swift files, including your PaymentCriteria.swift file. Then you try using PaymentCriteria back in objc, which leads to adding it to umbrella header. And generally because of such a path I experienced similar errors.

The simplest workaround would be creation AccountCriteria as a protocol using Swift with @objc .

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