Need clarification on AnyObject in Swift

不想你离开。 提交于 2019-12-22 13:12:52

问题


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 :)


回答1:


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


来源:https://stackoverflow.com/questions/31766773/need-clarification-on-anyobject-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!