3

For instance, I want to extract a Swift protocol from my existing Objective-C class MyFoo. Let's call this protocol 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". 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?

fatuhoku
  • 4,815
  • 3
  • 30
  • 70
  • `MyFoo` needs a base class, otherwise the Objective-C code does not compile. `let theFoo: Foo = ` should probably be `let theFoo: FooProtocol = `. – And then your code *does* compile in both Xcode 6.4 and Xcode 7 GM. – Is that your real code? – Martin R Sep 12 '15 at 19:44
  • 1
    you are redeclaring class property in protocol extension. swift won't know which should be run – Mousavian Sep 12 '15 at 22:16
  • @MartinR thanks, I updated the question. No, it's not my real code. I'l need to set up a test project and try... surprising, because in my real project I did exactly that and I keep getting the error. – fatuhoku Sep 14 '15 at 17:18
  • 1
    @fatuhoku: If your posted code does not exhibit the problem, how can anyone answer the question? – Martin R Sep 14 '15 at 17:41

1 Answers1

0

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!
}
Bell App Lab
  • 818
  • 6
  • 14