2

When defined as below in Objective-C code, how can I specify Item protocol from Swift?

// Objective-C
@protocol Item <NSObject>
@end

@interface Item : NSObject<Item>
@end

@implementation Item
@end



// Swift
var item = Item() // item interface, but I'd like to define as Item protocol.

Should I define as distinct name?

1
  • It would be easier when you use 2 different names for the protocol and the class. But it will work with the explicit type like akashivskyy said. variable of type Item and conforms to a protocol also named Item... confusing though. Commented Aug 28, 2014 at 11:25

1 Answer 1

5

You cannot instantiate a protocol type, therefore Item() will always refer to @interface Item. You should explicitly specify that you mean a protocol in your declaration:

var item: protocol<Item>

By the way, the thing you've done in Objective-C cannot be done in Swift – it requires all declarations in the same scope to be uniquely named. Your equivalent, following Apple's conventions, would look like this:

@objc(Item) protocol ItemType {

}

class Item: ItemType {

}
Sign up to request clarification or add additional context in comments.

5 Comments

Thnaks, but if the class name and protocol name is same, when specifying from Swift, the compiler show the error: "Non-protocol type 'Item' cannot be used within 'protocol<...>'". Should class name and protocol name is not same if I'd like to refer from Swift?
In my opinion – yes. Apple renamed its NSObject protocol into NSObjectProtocol for the same reason.
Just use ItemType or ItemProtocol in your Objective-C code and it will become more safe and readable.
I noticed that, if protocol name and class name is same on Objective-C code, XxxProtocol is automatically generated on Swift code, so I can specify the protocol by using that.
Oh, that's one more hidden gem I didn't know about, thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.