3

例如,我想从我现有的 Objective-C 类中提取一个 Swift 协议MyFoo。我们称之为协议FooProtocol

情况如下所示:

// 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!
}

然后我应该被允许这样做:

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

但是我被告知“MyFoo 不符合协议 FooProtocol”。好的。很公平,我猜协议扩展需要一点推动:

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

但我从编译器中收到看起来像的错误

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

我究竟做错了什么?

4

1 回答 1

0

这些接口具有不同的签名,因此编译器并不真正知道该做什么。

尝试这个:

// 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!
}
于 2015-12-21T18:12:41.780 回答