Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing types with Swift

Tags:

ios

swift

I'm looking to do something like the following, but when I try to see if b == Test.self I get the error "Any class is not convertible to MirrorDisposition". How can I checked to see if a Type is equal to another type?

class Test {  }  var a = Test.self  var b : AnyClass = a  if(b == Test.self) {     println("yes") } else {     println("no") } 
like image 991
puttputt Avatar asked Jan 08 '15 21:01

puttputt


People also ask

How do I compare two classes in Swift?

The == Operator In Swift, variables can be value types or reference types. The first “family” of variables holds values, whereas the second holds memory references. So if you're using objects instantiated by a class schema, the == operator compares references and not values.

What is == and === in Swift?

The difference between == and === in Swift is: == checks if two values are equal. === checks if two objects refer to the same object.

What does the === operator do in Swift?

The === or identity operator compares the identity of the objects. It checks whether the operands refer to the same object. As you can see, arr1 and arr2 do not refer to the same object, despite the objects being equal.


2 Answers

Use the "identical to" operator ===:

if b === Test.self {     print("yes") } else {     print("no") } 

This works because the type of a class is itself a class object and can therefore be compared with ===.

It won't work with structs. Perhaps someone has a better answer that works for all Swift types.

like image 91
Martin R Avatar answered Oct 17 '22 00:10

Martin R


if b.isKindOfClass(Test) {     println("yes") } else {     println("no") } 

Edit: Swift 3

if b.isKind(of: Test.self) {     print("yes") } else {     print("no") } 

try it :)

like image 27
Long Pham Avatar answered Oct 16 '22 23:10

Long Pham