Thomas Clowes Thomas Clowes - 1 year ago 108
Swift Question

Swift too smart? Checking an objects type when testing with XCTest

I am aware there are a number of questions on how to get the type of an object using Swift.

For example: How do you find out the type of an object (in Swift)?

The reason that I want to find the type is so that I can test that the correct thing is returned within a unit test. The premise being if anyone ever changes it, the test will fail, and we will know to be more careful.

Swift has the

method which returns a boolean as to whether an object is of a certain type. I would like to use is, and then assert that the response is true.

As outlined here ( however, and shown in practice.. this throws up an error:

error: 'is' test is always true

The point is that it returns true now.. and i am writing a test so that this is always the case. Stupid swift.

Any ideas how I can test the type of a response using XCTest and swift?


Answer Source

To get around Swift being too smart, cast the item you are testing to type Any and then test it. For instance, if you want to assert that the function fred() returns an Int

func fred() -> Int {
    return 3

assert((fred() as Any) is Int)

Try this in a Playground, and then change the return type to Float and the assert will fire.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download