Swift 测试一个类型是否与另一个类型兼容

标签 swift

想象一下以下情况:

class Car {
}

class Mercedes: Car {
}

let aCarType: Any.Type = Mercedes.self

如何测试 aCarType 中表示的类型是否继承Car

aCarType is Car.Type

当然,返回值总是 false。

在我的情况下,Objective-C 动态是不可能的! aCarType 填充在我无法控制的代码中。

最佳答案

使用 is 运算符和 Type 检查一个类是否等于另一个类 is 的子类的 Swift 方法属性(property)。这是一个例子:

let c: Any.Type = UIButton.self        
print(c is UIButton.Type) // true
print(c is UIView.Type) // true
print(c is UILabel.Type) // false

因此,您问题中的语句 aCarType is Car.Type始终评估为 true。我验证了最新版本的 Xcode 6 (Swift 1.2) 和 Xcode 7 (Swift 2) 中确实存在这种情况。

关于Swift 测试一个类型是否与另一个类型兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32536771/

相关文章:

ios - 返回主视图 Controller 后如何完全关闭 View Controller

swift - 在进行 POST 之前等待找到坐标

swift - 检测何时通过拖放删除了 NSStatusItem

swift - Swift 中的数学除法

swift - __NSCFString nsli_lowerAttribute :intoExpression:withCoefficient:forConstraint: this occur in ios 10 only

swift - 代码在 Playground 上运行良好;同时它产生一个 EXC_I386_GPFLT 错误

ios - Swift 通知 - 触发日期后的重复间隔

ios - 按下行时不会调用 didSelectRowAtIndexPath

ios - Xcode Swift 回到上一个viewController(TableViewController)

swift - 为什么我尝试在 mac 终端中使用 $ swift 运行 swift 语言时出现错误