Comparing literal type in swift fails?

This code runs Swift 3:

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

However, great, this code does not work:

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

What is the syntax for performing the second comparative work, if any?

Many thanks.

+7
reflection swift swift3
source share
1 answer

I think the error message is misleading. The real problem was how to interpret literal 1 in the second call. Swift defaults to Int when defining a variable:

 let a = 1 // a is an Int 

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

 func takeADouble(value: Double) { ... } func takeAUInt(value: UInt) { ... } takeADouble(value: 1) // now it a Double takeAUInt(value: 1) // now it a UInt 

type(of:) is defined as a generic function:

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

The compiler has no idea how to interpret the general Type parameter: should it be Int , UInt , UInt16 , etc.? Here is the error I received from 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 telling it what type it is:

 type(of: 1 as Int) == Int.self 
+4
source share

All Articles