在 Objective C 中,@interface 和@protocol 可以同名。如何在 Swift 中创建一个仅采用协议(protocol)的类?
@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
如何在没有子类 class NICellObject 的情况下采用 protocol NICellObject
最佳答案
当您将 objective-c 类导入 swift 时,“协议(protocol)”将自动附加到协议(protocol)名称。所以你应该只采用 XXXXXProtocol。
我刚刚在我的本地项目中尝试过。在你的例子中是 NICellObjectProtocol。
编辑前的旧答案
你误会了,它们是同名的两个不同的东西。一个是名为 NICellObject 的协议(protocol),还有一个名为 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.
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.
而且在 Swift 中不可能做到这一点。我找不到这样说的文档,但从语言引用中得到一些提示,声明在您的程序中引入了新名称或契约(Contract)。
“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
关于ios - 如何实现与另一个类同名的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26735696/