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

agr*_*986 7 reflection swift swift3

这段代码适用于Swift 3:

let a = 1
type(of: a) == Int.self // true
Run Code Online (Sandbox Code Playgroud)

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

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

如果有的话,第二次比较的语法是什么?

非常感谢.

Cod*_*ent 4

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

let a = 1 // a is an Int
Run Code Online (Sandbox Code Playgroud)

但编译器可以根据上下文将其读为DoubleUInt32、等:CChar

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

takeADouble(value: 1) // now it's a Double
takeAUInt(value: 1)   // now it's a UInt
Run Code Online (Sandbox Code Playgroud)

type(of:)定义为通用函数:

func type<Type, Metatype>(of: Type) -> Metatype
Run Code Online (Sandbox Code Playgroud)

编译器不知道如何解释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), ...
Run Code Online (Sandbox Code Playgroud)

您可以通过告诉编译器它是什么类型来给它一些帮助:

type(of: 1 as Int) == Int.self
Run Code Online (Sandbox Code Playgroud)