Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 is 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 (http://www.raywenderlich.com/74138/swift-language-faq) 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?

Thanks

like image 570
Thomas Clowes Avatar asked Sep 08 '14 13:09

Thomas Clowes


Video Answer


1 Answers

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.

like image 106
vacawama Avatar answered Oct 09 '22 15:10

vacawama