简体   繁体   中英

How to compare types in Swift?

I declare two variables in a Swift file, with the following values:

let m = 1
let n = 2

Now, I would like to compare their types:

type(of: m) === type(of: n)

The following compliling error occurs:

Argument type 'String.Type' expected to be an instance of a class or class-constrained type

Is there a way to compare types?

Also, why does this line fail?

String === String

The === operator is only defined for reference types, since it checks reference (pointer) equality, so you can't use it on metatypes of value types.

However, you can use the normal equality operator, == .

type(of: m) == type(of: n)

As for String === String , that's not even valid code. What you need if String.self == String.self . You can access metatypes using TypeName.self .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM