比较swift中的文字类型失败了吗?

时间:2017-03-22 07:04:01

标签: swift reflection swift3

此代码的工作原理是Swift 3:

let a = 1
type(of: a) == Int.self // true

但是,这段代码显然失败了:

// error: binary operator '==' cannot be applied to two 'Int.Type' operands
type(of: 1) == Int.self

使第二次比较有效的语法是什么?

非常感谢。

1 个答案:

答案 0 :(得分:4)

我认为错误信息具有误导性。真正的问题是如何解释第二次调用中的文字1。定义变量时,Swift默认为Int

let a = 1 // a is an Int

但编译器可以将其读作DoubleUInt32CChar等,具体取决于上下文:

func takeADouble(value: Double) { ... }
func takeAUInt(value: UInt) { ... }

takeADouble(value: 1) // now it's a Double
takeAUInt(value: 1)   // now it's a UInt

type(of:)defined作为通用函数:

func type<Type, Metatype>(of: Type) -> Metatype

编译器不知道如何解释Type泛型参数:它应该是IntUIntUInt16等吗?这是我从IBM Swift Sandbox得到的错误:

Overloads for '==' exist with these partially matching parameter lists
(Any.Type?, Any.Type?), (UInt8, UInt8), (Int8, Int8),
(UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), ...

你可以通过告诉它它是什么类型来给coompiler一些帮助:

type(of: 1 as Int) == Int.self