2016-04-05 19 views
1

为什么这个函数不能编译?抱怨是:二元运算符'==='不能用于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) 

回答

1

您可能需要的参数来约束作为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 
+0

这听起来并不正确。查看我添加到我的问题中的对比例。 – Verticon

+0

等一下;现在我懂了。如果没有AnyObject约束,T和I可以是结构或枚举;无法应用===运算符。 – Verticon

+0

非常适合你!你能提出答案吗? – mohamede1945