加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 在Obj-C中使用Swift协议的实现

发布时间:2020-12-16 03:43:09 所属栏目:百科 来源:网络整理
导读:我正在尝试使用 Swift和Obj-C的混合实现一种中介类型的模式.我面临的问题是如何处理使用Obj-C的Swift协议实现类.看看代码,看看我的意思: Swift协议及其实现: @objc public protocol TheProtocol { func someMethod()}@objc public class SwiftClass: NSObj
我正在尝试使用 Swift和Obj-C的混合实现一种中介类型的模式.我面临的问题是如何处理使用Obj-C的Swift协议实现类.看看代码,看看我的意思:

Swift协议及其实现:

@objc public protocol TheProtocol {
    func someMethod()
}

@objc public class SwiftClass: NSObject,TheProtocol {
    public func someMethod() {
        print("someMethod Swift")
    }
}

ObjC-协议的实施:

#import "SwiftAndObjC-Swift.h"
@interface ObjCClass : NSObject <TheProtocol>
- (void) someMethod;
@end


@implementation ObjCClass
- (void) someMethod
{
    NSLog(@"someMethod ObjC");
}
@end

我的问题是如何在ObjC中定义一些能够引用SwiftClass或ObjCClass的类型.例如,这不编译:

#import "SwiftAndObjC-Swift.h"
...
TheProtocol *p = [[ObjCClass alloc] init];
// Error: "Use of undeclared identifier TheProtocol"

这将编译:

@class TheProtocol
TheProtocol *p = [[ObjCClass alloc] init];

但不能使用p:

@class TheProtocol
TheProtocol *p = [[ObjCClass alloc] init];
[p someMethod];
// Error: Receiver type "The Protocol" is a forward declaration"

(将转换添加到赋值和/或方法调用没有帮助)

有解决方案吗

解决方法

在Objective-C中,协议不是一种类型.您应该声明符合协议的类,如下所示:
id<TheProtocol> p = [[ObjCClass alloc] init];

你的前向声明编译的原因是因为这是前向声明的作用 – 它们向编译器宣告一个类存在,并且链接器将在稍后的构建过程中填充它.

(这就是改为id p = …的原因.)

在Swift中,我们使用类似的东西声明类:

class MyClass : Superclass,Protocol,AnotherProtocol { ... }

在Objective-C中,我们使用:

@class MyClass : SuperClass <Protocol,AnotherProtocol>
// ... 
@end

看到不同?在Swift中,协议和超类被混合到继承声明中,而Objective-C则以非常不同的方式处理它们.

两种语言对协议和类的处理略有不同,因此使用方式不同.

ObjectiveC中的id类似于AnyObject?在斯威夫特.符合SomeProtocol的对象显然是Objective-C中的AnyObject或id.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读