Comparing type of literal in swift fails?

This code works is Swift 3:

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

However, remarkably this code fails:

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

What is the syntax to make the second comparison work, if any?

Thanks a lot.


I think the error message was misleading. The real issue was how to interpret the literal 1 in the second call. Swift defaults to an Int when you define a variable:

let a = 1 // a is an Int

But the compiler can read it as Double , UInt32 , CChar , etc. depending on the context:

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:) is defined as a generic function:

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

The compiler has no clue on how to interpret the Type generic parameter: should it be an Int , UInt , UInt16 , etc.? Here's the error I got from the 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), ...

You can give the coompiler some help by tell it what type it is:

type(of: 1 as Int) == Int.self
链接地址: http://www.djcxy.com/p/95828.html

上一篇: isSelected总是返回false

下一篇: 比较swift中的文字类型失败?