需要澄清Swift中的AnyObject

时间:2015-08-01 22:21:12

标签: swift casting nsobject typecast-operator

在开始之前,我已经阅读过Swift文档了。我仍然想要理解 AnyObject 实际上是什么。它是Swift中所有对象/类的基类,因为 NSObject 是在Objective C中吗?

如果我创建一个 [AnyObject] 类型的数组,并用 Movie 类实例填充它,那就意味着 AnyObject 是一个基础电影类的课程对吗?

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

这应该是正确的,否则您将无法使用类型转换运算符< as! 向下转换对吗?

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

Swift文档指出:

  

AnyObject可以表示任何类类型的实例。

所以...在AnyObject是基类实例的意义上表示它?

我是Swift的新手所以请耐心等待:)。

1 个答案:

答案 0 :(得分:4)

AnyObject是一种协议。如果您在Playground中键入它并命令单击它,则会弹出以下内容:

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