简体   繁体   English

在Swift中,Objective-C类的属性是否可以满足Swift @obj协议计算属性要求?

[英]In Swift, is it possible for a Objective-C class' properties to satisfy a Swift @obj protocol computed property requirement?

For instance, I want to extract a Swift protocol from my existing Objective-C class MyFoo . 例如,我想从现有的Objective-C类MyFoo提取Swift协议。 Let's call this protocol FooProtocol . 我们称这个协议为FooProtocol

The situation looks like this: 情况如下:

// In Objective-C
@interface MyFoo
@property(nonatomic, copy) NSString *foo;
@end
@implementation MyFoo
// ... -(instancetype)initWithString: is implemented here
@end

// In Swift
@objc protocol FooProtocol {
    var foo: String { get set }
}

extension MyFoo: FooProtocol {
    // do nothing here!
}

Then I should be allowed to do this: 然后我应该被允许这样做:

let theFoo: FooProtocol = MyFoo(string: "Awesome")
NSLog("\(theFoo.foo)") // Prints awesome.

But I get told "MyFoo does not conform to protocol FooProtocol". 但我被告知“MyFoo不符合协议FooProtocol”。 Okay. 好的。 Fair enough, I guess the protocol extension needs a little nudge: 很公平,我想协议扩展需要一点点推动:

extension MyFoo: FooProtocol {
    var foo: String! { get { return foo } set { NSLog("noop") }}
}

but I'm getting errors from the compiler that look like 但我从编译器看到的错误

Getter for 'foo' with Objective-C selector 'foo' conflicts with previous declaration with the same Objective-C selector

What am I doing wrong? 我究竟做错了什么?

The interfaces have different signatures and therefore the compiler doesn't really know what to do. 接口具有不同的签名,因此编译器实际上不知道该怎么做。

Try this: 尝试这个:

// In Objective-C
@interface MyFoo
@property(nonatomic, copy) NSString *foo;
@end
@implementation MyFoo
// ... -(instancetype)initWithString: is implemented here
@end

// In Swift
@objc protocol FooProtocol {
    var foo: NSString { get set }
}

extension MyFoo: FooProtocol {
    // do nothing here!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM