swifttype-aliasanyobject

Swift: Confused about AnyObject declaration


I know AnyObject can be any class type, but what I'm confused about is the declaration of AnyObject, I have read a book and some articles saying it's a protocol, but when I looked at AnyObject declaration it shows me that it is a typealias AnyObject not a protocol, and if we supposed that typealias AnyObject is assigned to some protocols (Ex: typealias AnyObject = some protocols here) I can not see what protocols the typealias AnyObject is assigned to, please help.


Solution

  • Formerly, Swift.AnyObject was an empty protocol defined in Policy.swift and known to the compiler. On April 13, 2017, Slava Pestov changed it to the current typealias and removed knowledge of Swift.AnyObject from the compiler.

    Currently, Swift.AnyObject is a typealias, declared in Policy.swift in the standard library source code:

    public typealias AnyObject = Builtin.AnyObject
    

    Builtin is a special module that contains types and functions that are built in to the compiler. Members of the Builtin module don't have to be declared in Swift. Normal source code cannot access the Builtin module directly. The standard library is compiled in a special compiler mode that gives it access to the Builtin module.

    The compiler deals with the Builtin.AnyObject type in swift::getBuiltinType in lib/AST/Builtins.cpp:

      // AnyObject is the empty class-constrained existential.
      if (Name == "AnyObject")
        return CanType(
          ProtocolCompositionType::get(Context, {},
                                       /*HasExplicitAnyObject=*/true));
    

    So Builtin.AnyObject is (somewhat paradoxically) a protocol composition containing no protocols as members (that's the {} argument), and flagged as being a reference type (that's the true argument).

    What's a “protocol composition”? In Swift, you can declare that a variable's type is multiple protocols put together:

    protocol P { }
    protocol Q { }
    var v: P & Q    // v's type is the composition of protocols P and Q
    

    There is no way to write an empty protocol composition (a composition containing no protocols) in the Swift language.