此[AnyObject]如何返回为AnyObject? [英] How can this [AnyObject] return as AnyObject?

查看:76
本文介绍了此[AnyObject]如何返回为AnyObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import Cocoa

class Brain{
    var internalProgram = [AnyObject]()
    var program:AnyObject{
        get{
            return (internalProgram as AnyObject)
        }
    }
}

var savedProgram: AnyObject?
let brain = Brain()
func save(){
    savedProgram = brain.program
}

内部程序:[AnyObject] 如何返回为 AnyObject 而没有Xcode给出警告或错误?我知道程序的类型已经设置为 AnyObject ,但是我的意思是这如何工作,不是吗应该是 [AnyObject] ?那么为什么没有任何警告或错误问题呢?

How can this internalProgram:[AnyObject] return as AnyObject without Xcode giving a warning or an error? I know that program's type is set as AnyObject already but I mean how can this work and wasn't it supposed to be [AnyObject]? So why no any warning or error issue?

推荐答案


那么为什么没有任何警告或错误问题?

So why no any warning or error issue?

如果您没有将称为AnyObject ,那将会是:

There would have been if you hadn't of said as AnyObject:

class Brain {
    var internalProgram = [AnyObject]()
    var program: AnyObject {
        get {
            // compiler error:
            // Return expression of type '[AnyObject]' does not conform to 'AnyObject'
            return internalProgram
        }
    }
}

编译器告诉我们 [AnyObject] AnyObject 不符–完全正确。 Swift Array 结构,而不是,因此,不能直接将其键入为 AnyObject

The compiler is telling us that [AnyObject] doesn't conform to AnyObject – which is perfectly true. A Swift Array is a struct, not a class, therefore cannot directly be typed as an AnyObject.

但是,然后将称为AnyObject 。这样,您就可以将Swift Array 桥接到 NSArray (当Foundation是导入的)– 。因此,可以将其键入为 AnyObject 。您可以看到可以桥接到此处

However, you then say as AnyObject. By doing so, you're bridging the Swift Array to NSArray (when Foundation is imported) – which is a class. Therefore it can be typed as an AnyObject. You can see the full list of Foundation types which can be bridged to here.

此外,值得注意的是,在Swift 3中, 所有内容都可以桥接到 AnyObject 由于引入了不透明的 _SwiftValue 类型,该类型可以将任意Swift值包装在与Obj-C兼容的框中(包括 Array (当未导入Foundation时)。

Furthermore it's worth noting that in Swift 3, everything can be bridged to AnyObject due to the introduction of the opaque _SwiftValue type, which can wrap an arbitrary Swift value in an Obj-C compatible box (including Array when Foundation isn't imported).

因为任何内容现在都可以是 AnyObject ,它的类型几乎与 Any 一样弱。最重要的是,它还允许您在其上调用任何已知的 @objc 方法,完全不考虑类型安全性,并且几乎可以保证会导致您遇到问题使用 _SwiftValue 拳击。由于这些原因,应避免在任何可能的地方使用 AnyObject 几乎总是有更强的类型供您使用。

Because anything can now be an AnyObject, it's pretty much as weak a type as Any. On top of this, it also lets you call any known @objc method on it, completely disregarding type safety and is almost guaranteed to cause you problems with _SwiftValue boxing. For those reasons, you should avoid using AnyObject wherever you can. There is nearly always a stronger type available for you to use.

这篇关于此[AnyObject]如何返回为AnyObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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