需要澄清AnyObject在Swift [英] Need clarification on AnyObject in Swift

查看:163
本文介绍了需要澄清AnyObject在Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

如果我创建 [AnyObject] 类型的数组并使用 Movie 类实例填充, AnyObject 电影类别的基类吗?

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")
]

这应该是真的,否则你不能使用类型转换操作符( as!

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)")
}

Swift文档规定:

The Swift documentation states:


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

AnyObject can represent an instance of any class type.

所以...表示AnyObject是一个基类实例?

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

我是Swift新手,请耐心等待)

I am new to Swift so please have patience :)

推荐答案

AnyObject 是一种协议。如果你在Playground中输入它,并点击它,弹出如下:

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

这篇关于需要澄清AnyObject在Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆