Swift 中的关键字 Protocol(大写 P)是什么

dis*_*ute 2 foundation swift

刚发现可以Protocol直接打字,和其他两种情况的Type不一样
在此处输入图片说明

实际上,您可以尝试初始化它并收到一条错误消息,提示某种提示
在此处输入图片说明

但是ProtocolSwift 到底做了什么?

Mar*_*n R 5

Protocol是一个在 Objective-C 运行时中定义的,代表一个 Objective-C 协议。例子:

let p = objc_getProtocol("NSObject")! 
print(p.dynamicType) // Output: "Protocol"
Run Code Online (Sandbox Code Playgroud)

objc_getProtocol 被声明为

/** 
 * Returns a specified protocol.
 * 
 * @param name The name of a protocol.
 * 
 * @return The protocol named \e name, or \c NULL if no protocol named \e name could be found.
 * 
 * @note This function acquires the runtime lock.
 */
@available(OSX 10.5, *)
public func objc_getProtocol(name: UnsafePointer<Int8>) -> Protocol!
Run Code Online (Sandbox Code Playgroud)

并被Protocol声明为

// typedef Protocol is here:

// All methods of class Protocol are unavailable. 
// Use the functions in objc/runtime.h instead.

@available(OSX 10.0, *)
public class Protocol {
}
Run Code Online (Sandbox Code Playgroud)

底层的 Objective-C 定义可以在<objc/Protocol.h> 和 中 找到 <objc/runtime.h>

  • 我正要开始输入答案。猜猜我现在不必了。我要添加的唯一一件事是指出最明显的用例是将 `Protocol` 用作 `NSObject` 的 `conformsToProtocol:` 类方法中的参数类型。 (2认同)