Swift 如何在编译时解决这个问题?

How is Swift resolving this at compile time?

这是我在 Swift 编码的第二天,所以我很新。我在网上获得了以下代码,它使用 Apple API 在 iOS 设备上枚举了 audio/video 设备:

let devices = AVCaptureDevice.devices()

// Loop through all the capture devices on this phone
for device in devices {

    // Make sure this particular device supports video
    if (device.hasMediaType(AVMediaTypeVideo)) {
        ...
    }
}

现在,如果我查找 AVCaptureDevice.devices() returns,我会在 Apple 文档中找到:

class func devices() -> [AnyObject]!

所以这肯定意味着设备是 AnyObject 类型(非常通用的类型)和高度专业化的调用 device.hasMediaType(...) 我猜必须在更多的地方实现专门的子类应该是不可能的。我预计 AnyObject 没有名为 hasMediaType 的函数的错误(我很确定它没有)。

那么这为什么有效?甚至自动完成功能似乎也为我提供了编辑器中的 hasMediaType() 功能。我的理解是这不应该是可能的。

AnyObject 表示所有已知的 Objective-C 方法和属性都可用(参见 here)。

您会注意到所有内容 都是作为自动完成提供的。它等同于在 Objective-C 中使用 id

如果您使用 AVCaptureDevice 未实现的方法,您仍将获得自动完成功能,但会在运行时崩溃。

Apple 在可能的情况下逐渐将所有这些替换为类型化数组,因此最终将消除这种歧义。

如果你看看什么是 AnyObject,你会发现这样的文档

@objc protocol AnyObject

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.

例如

class A:NSObject{
    func a_test(){

    }
}

然后你打电话

  var b:AnyObject?;
  b?.a_test(); 

This is OK in XCode,just be compiled to send message to object b,but will crash at runtime

因为,任何对象在Objective C中是id,并且是"Sending message to a object"左右,它会被Objective C运行时解决