简体   繁体   中英

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

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

只需在协议名称中添加一个Protocol后缀,以区分ClassProtocol

class A: BaseObject, NICellObjectProtocol { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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