Search code examples
swiftcastingnsobjecttypecast-operator

Need clarification on AnyObject in Swift


Before I start, I have already read the Swift documentation. I am still trying to comprehend what AnyObject actually is. Is it a base class for all objects/classes in Swift, as NSObject is in Objective C?

If I create an array of type [AnyObject] and populate it with Movie class instances, that would mean that AnyObject is a base class of the Movie class right?

let someObjects: [AnyObject] = [
    Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"),
    Movie(name: "Moon", director: "Duncan Jones"),
    Movie(name: "Alien", director: "Ridley Scott")
]

This should be true or else you wouldn't be able to downcast with the type casting operator (as!) right?

for object in someObjects {
    let movie = object as! Movie
    println("Movie: '\(movie.name)', dir. \(movie.director)")
}

The Swift documentation states:

AnyObject can represent an instance of any class type.

So...represent it in the sense that AnyObject is a base class instance?

I am new to Swift so please have patience :)


Solution

  • AnyObject is a protocol. If you type it in a Playground and command click on it the following pops up:

    /// The protocol to which all classes implicitly conform.
    ///
    /// When used as a concrete type, all known `@objc` methods and
    /// properties are available, as implicitly-unwrapped-optional methods
    /// and properties respectively, on each instance of `AnyObject`.  For
    /// example:
    ///
    /// .. parsed-literal:
    ///
    ///   class C {
    ///     @objc func getCValue() -> Int { return 42 }
    ///   }
    ///
    ///   // If x has a method @objc getValue()->Int, call it and
    ///   // return the result.  Otherwise, return nil.
    ///   func getCValue1(x: AnyObject) -> Int? {
    ///     if let f: ()->Int = **x.getCValue** {
    ///       return f()
    ///     }
    ///     return nil
    ///   }
    ///
    ///   // A more idiomatic implementation using "optional chaining"
    ///   func getCValue2(x: AnyObject) -> Int? {
    ///     return **x.getCValue?()**
    ///   }
    ///
    ///   // An implementation that assumes the required method is present
    ///   func getCValue3(x: AnyObject) -> **Int** {
    ///     return **x.getCValue()** // x.getCValue is implicitly unwrapped.
    ///   }
    ///
    /// See also: `AnyClass`
    @objc protocol AnyObject {
    }