swiftfoundation

what is the keyword Protocol (capital P) do in Swift


Just found you can type Protocol directly, and its Type different from other 2 cases
enter image description here

actually you can try init it and got a error message that some kind of hint something
enter image description here

but what on earth does the Protocol do in Swift?


Solution

  • Protocol is a class which is defined in the Objective-C runtime and represents an Objective-C protocol. Example:

    let p = objc_getProtocol("NSObject")! 
    print(p.dynamicType) // Output: "Protocol"
    

    objc_getProtocol is declared as

    /** 
     * 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!
    

    and Protocol is declared as

    // 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 {
    }
    

    The underlying Objective-C definitions can be found in <objc/Protocol.h> and <objc/runtime.h>.