检查对象types失败,出现“不是types”错误

我试图检查一个对象是否是给定的types,我得到一个错误:

'expectedClass'不是一个types

Xcode中

我的代码如下。

func testInputValue(inputValue: AnyObject, isKindOfClass expectedClass: AnyClass) throws { guard let object = inputValue as? expectedClass else { // Throw an error let userInfo = [NSLocalizedDescriptionKey: "Expected an inputValue of type \(expectedClass), but got a \(inputValue.dynamicType)"] throw NSError(domain: RKValueTransformersErrorDomain, code: Int(RKValueTransformationError.UntransformableInputValue.rawValue), userInfo: userInfo) } } 

我试图弄清楚这里可能是错的。

你应该可以用generics来做到这一点:

 func testInputValue<T>(inputValue: AnyObject, isKindOfClass expectedClass: T.Type) throws { guard let object = inputValue as? T else { ... } } 

除非你特别想testing被测对象的types是否应该与期望的类完全匹配,并且不允许它是被测类的子类,否则你不应该用==来进行类对比。 。

你可以使用实例方法isKindOfClass来实现这一点,考虑到子类。 请参阅下面的代码示例。

注意 :你可能会感到惊讶,因为NSObject / NSObjectProtocol存在一个具有相同名称的实例方法,所以这对纯Swift类types有效。 它确实在纯Swift中工作(如下面的示例代码所示 – 用Xcode 7.3,Swift 2.2.1testing),只要导入Foundation,不涉及任何@objctypes。 我假设基于此,这个实例方法被添加为所有类types的Foundation中的扩展方法。

 import Foundation class A { } class B { } class C: B { } enum ValueTestError: ErrorType { case UnexpectedClass(AnyClass) } func testInputValue(inputObj:AnyObject, isKindOfClass expectedClass:AnyClass) throws { guard inputObj.isKindOfClass(expectedClass) else { throw ValueTestError.UnexpectedClass(inputObj.dynamicType) } } let a = A() let b = B() let c = C() do { try testInputValue(c, isKindOfClass: B.self) } catch { print("This does not get printed as c is of type B (C is subclass of B).") } do { try testInputValue(a, isKindOfClass: B.self) } catch { print("This gets printed as a is not of type B.") } 

此外,重要的是,尽pipeisKindOfClass作为isKindOfClass上的一个实例方法是可用的,但试图在任意Swift类types对象上调用它时,只有当您首次将该对象转换为AnyObject时(这当然会成功),它才会起作用。 下面介绍说明这一点的示例代码,这里还有更多的关于这个问题。

 import Foundation class A {} let a = A() // the following compiles and returns 'true' (a as AnyObject).isKindOfClass(A.self) // the following fails to compile with "Value of type 'A' has no member 'isKindOfClass'" a.isKindOfClass(A.self) 

不是有史以来最伟大的答案,但与inputValue.dynamicType作品比较:

 if inputValue.dynamicType == expectedClass { print("inputValue.dynamicType \(inputValue.dynamicType) equals expectedClass \(expectedClass)") // ... }