Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
agro1986 Avatar asked Mar 22 '17 07:03

agro1986


1 Answers

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
like image 79
Code Different Avatar answered Sep 26 '22 14:09

Code Different