error after importing Swift into Objective-c

2020-04-18 09:06发布

问题:

I try to use swift in OC,so I set Defines Module YES set Product Module Name with Product Name and "import ProductName-Swift.h" in the .m file where i wanted to use swift

but the project cannot run ,cause a lot of mistakes in the "ProductName-Swift.h"

it seems something wrong with AppDelegate.swift,how to resolve this problem

回答1:

here is how I solved the problem into the ProductName-Swift.h : On this file, I can see the imports like that :

#if defined(__has_feature) && __has_feature(modules)
    @import UIKit;
    @import CoreGraphics;
    @import MessageUI;
    @import AddressBookUI;
    @import AddressBook;
    @import Foundation;
    @import ObjectiveC;
    @import MapKit;
    @import CoreLocation;
#endif

so, regarding the errors, I thought import doesn't work well. First, compiler doesn't come in the if. It appears the

__has_feature(modules)

return false (whereas I set it on my build settings).

Ok, let go without and... error again. It appears the @import can only be used when modules is activated and he found no.... so I replaced all @import by #import and it works !! But the last problem is the generation of the file each time I write in a swift file.. I have to change these import each... so I create this snippet code :

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AddressBookUI/AddressBookUI.h>
typedef ABRecordRef ABRecord;

(the last line is to replace ABRecord found in swift methods by ABRecordRef used in Objective-C)

Note : I don't have any #import for @import ObjectiveC but it seems it isn't needed.

PS : I'll create a post to ask help about the module set-but-not-for-compiler, if you think you have the answer.. ;-)



回答2:

I have the same problem with MapKit framework, compiler pointed on missed declaration of MKMapViewDelegate in ProductName-Swift.h file. To solve this problem i added #import <MapKit/MapKit.h> in bridge header file PoductName-Bridging-Header.h.

You can try to add UIApplicationDelegate to this header. I hope this will help you.