Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a protocol which has same name as another class

In Objective C, the @interface and @protocol can have same names. How to create a class in Swift to adopt only the protocol?

Nimbus NICellFactory.h

@interface NICellObject : NSObject <NICellObject>

// Designated initializer.
- (id)initWithCellClass:(Class)cellClass userInfo:(id)userInfo;
- (id)initWithCellClass:(Class)cellClass;

+ (id)objectWithCellClass:(Class)cellClass userInfo:(id)userInfo;
+ (id)objectWithCellClass:(Class)cellClass;

@property (nonatomic, strong) id userInfo;

@end

How to adopt the protocol NICellObject without subclass class NICellObject

like image 336
aelam Avatar asked Nov 04 '14 12:11

aelam


2 Answers

When you import the objective c class into swift, "Protocol" will be automatically append to the name of the protocol. So you should just adopt the XXXXXProtocol.

I just tried it in my local project. In your case NICellObjectProtocol.

OLD ANSWER BEFORE EDIT

You take it wrong, they are two different thing with the same name. One is protocol named NICellObject, and a class also named NICellObject.

How to implement two protocols in swift with one protocol also is a class In Nimbus there is NICellObject which is a protocol and a class, see the code below. There must have many same cases.

From this link, https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html.

Some protocols group a number of unrelated methods (rather than create several separate small protocols). These protocols tend to be associated with a class that is the principal expression of the protocol. In these cases, the convention is to give the protocol the same name as the class.

And it is not possible to do this in Swift. I can't find the document saying so, but some hint From the language reference, declaration introduces a NEW name or contract into your program.

“A declaration introduces a new name or construct into your program. For example, you use declarations to introduce functions and methods, variables and constants, and to define new, named enumeration, structure, class, and protocol types. You can also use a declaration to extend the behavior of an existing named type and to import symbols into your program that are declared elsewhere.

摘录来自: Apple Inc. “The Swift Programming Language”。 iBooks. https://itun.es/cn/jEUH0.l

like image 52
Shuo Avatar answered Nov 14 '22 23:11

Shuo


Just add a Protocol suffix to the protocol name, to distinguish the Class and the Protocol:

class A: BaseObject, NICellObjectProtocol { }
like image 40
Elf Sundae Avatar answered Nov 14 '22 23:11

Elf Sundae