Objective-c类是否有可能在.h中实现swift协议

时间:2016-08-23 22:20:31

标签: ios objective-c swift

Objective-C类是否可以在Swift中实现.h协议,以便其他Swift类可以引用Objective-CSwift协议类型?

MySwiftProtocol成为Swift协议类型,现在假设我在.h为我的班级提供此内容:

@protocol MySwiftProtocol;
@interface MyObj : NSObject< MySwiftProtocol>

然后我会收到警告:cannot find protocol definition for MySwiftProtocol
警告不好,所以不起作用。

因此,我假设我在.m中执行此操作,并删除.h中对协议的引用。

@interface MyObj () <MySwiftProtocol>

然后我最终无法将MyObj类型的对象转换为MySwiftProtocol类中的Swift类型。

因此上述方法均无效。

请帮忙!

1 个答案:

答案 0 :(得分:1)

根据苹果。 Forward declarations of Swift classes and protocols can only be used as types for method and property declarations。苹果说,An Objective-C class can adopt a Swift protocol in its implementation (.m) file by importing the Xcode generated header for Swift code...

基本上你不能将obj-c类标记为符合.h中的swift协议。因此,您必须在.m中执行此操作,然后让类将其自身传递给任何期望将objc对象作为swift协议类型引用的对象。

请参阅https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

上的Referencing a Swift Class or Protocol in an Objective-C HeaderAdopting a Swift Protocol in an Objective-C Implementation部分
相关问题