swift - 编译器不允许我比较类型

标签 swift

为什么这个函数不能编译?提示是:二元运算符“===”不能应用于 I.Type 和 T.Type 类型的操作数。

   func checkTypeOf<I, T>(instance: I, type: T.Type) {
       print("\(instance) \(I.self === type ? "is" : "is not") a \(type)")
   }

相比之下,这里有一个编译运行的例子:

class Dog {
    @objc static var whatADogSays : String = "woof"
}
class NoisyDog : Dog {
}

func typeTester(d:Dog, _ whattype:Dog.Type) {
    print("The \(d.dynamicType) \(d.dynamicType === whattype ? "is" : "is not") a \(whattype)")
}

typeTester(NoisyDog(), Dog.self)

最佳答案

您可能需要将参数限制为 AnyType,因为 === 仅适用于 AnyObject。

func checkTypeOf<I: AnyObject, T: AnyObject>(instance: I, type: T.Type) {
    print("\(instance) \(I.self === type ? "is" : "is not") a \(type)")
}

这里是===操作符的定义

@warn_unused_result
public func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool

关于swift - 编译器不允许我比较类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36426673/

相关文章:

swift - 如何检查用户的电子邮件是否已验证?

swift - 如何修复此错误无法使用类型 'String' 的参数列表调用类型 '(Student)' 的初始值设定项

ios - 如何检查 AVPlayer 中的音频 channel 数?

ios - 使用 nil 必需属性保存上下文时,Core Data 自定义访问器崩溃

ios - 当我不注销就终止应用程序时,经过身份验证的用户是否保持登录状态?

ios - 使用 Speech kit ios 时由于未捕获的应用程序崩溃而终止应用程序

ios - 在自定义 UITextField 类中调用委托(delegate)方法

swift - 调用与自定义函数同名的内置函数

swift - 单元测试的 Xcode 9 代码覆盖率显示错误百分比

ios - 为什么在设备或模拟器中运行我的应用程序时屏幕是黑色的