ios - 如何实现与另一个类同名的协议(protocol)

标签 ios swift protocols

在 Objective C 中,@interface 和@protocol 可以同名。如何在 Swift 中创建一个仅采用协议(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

如何在没有子类 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.

从这个链接,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.

而且在 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/

相关文章:

objective-c - 协议(protocol)的重点是什么?

ios - 动态调整弹出窗口大小时防止动画

ios - 从 iOS 中的联系方式获取街道、城市、州、 zip 和国家/地区并填充到标签

ios - Xcode/Swift-无法解决乐器的内存问题

ios - 根据时间更改状态栏颜色

ios - 如何获取在 RxSwift 中点击了哪个按钮

ios - 为一个或另一个扩展具有多个约束的协议(protocol) - Swift

javascript - JavaScript 书签是否必须是有效的 URL?

iphone - 绘图线的优化,CAShapeLayer 的可能替代品

json - 快速搜索 JSON