Siehe Abschnitt Referenzieren einer Swift-Klasse oder eines Protokolls in einem Objective-C-Header unter https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html. Es klingt wie eine Empfehlung, aber der Compiler erzwingt das meiner Erfahrung nach. Ich war normalerweise in der Lage, das Problem zu umgehen, indem ich Vorwärtsdeklarationen verwendete, wie in der oben erwähnten Apple-Veröffentlichung beschrieben, wenn ich wirklich eine Swift-Klasse in einer Kopfzeile und nicht in einer Quelldatei verwenden musste.
Hier ist ein stark vereinfachtes Beispiel. Zuerst einige Swift Code:
import Foundation
// A Swift protocol usable in Objective-C
@objc protocol MySwiftProtocol
{
func mySwiftProtocolFun();
}
// A Swift class conforming to the Swift protocol
class MySwiftClass : NSObject, MySwiftProtocol
{
func mySwiftProtocolFun() {
print("Hello from MySwiftClass!")
}
}
// Call an Objective-C function
aFunctionOC()
Als nächstes ist ein Objective-C-Header, der das Swift-Protokoll verwendet:
#import "Foundation/Foundation.h"
// Forward declaration of a Swift protocol is OK here
@protocol MySwiftProtocol;
@interface MyClassOC : NSObject
// Here we've got a property conforming to the Swift protocol
@property id<MySwiftProtocol> prop1;
-(void)callSwiftProtocol;
@end
Implementierung von MyClassOC
:
#import "objc.h"
#import "cli_swift-Swift.h"
@implementation MyClassOC
-(void)callSwiftProtocol
{
[self.prop1 mySwiftProtocolFun];
}
@end
Eine andere Objective-C-Klasse MyClassOC
:
#import "objc.h"
#import "cli_swift-Swift.h"
// An Objective-C function that uses an Objective-C class
// that has a property conforming to a Swift protocol
void aFunctionOC()
{
MyClassOC * x = [[MyClassOC alloc] init];
x.prop1 = [[MySwiftClass alloc] init];
[x callSwiftProtocol];
}
Schließlich ist hier ein Brückenkopf aFunctionOC()
zu Swift aussetzt:
void aFunctionOC();
so Objective-C oder swift? Es ist ein großer Unterschied –
Wenn Sie sich auf die Frage-Tags beziehen, sind beide enthalten, da die Frage die Integration von Swift-Code mit Objective-C ist. – aneuryzm
Versuchen Sie, Bridging-Header wie folgt in Build-Einstellungen 'MyApp_Swift.h' –