Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, could not cast value of type

Tags:

ios

swift

I created a subclass of UICollectionViewController and called it LibraryCollectionViewController, and marked both checkboxes for the project and test. Also it's storyboard id is LibraryCollectionViewController and set its corresponding class on interface builder.

Being new to Swift and iOS Testing I went and attempted to instantiate said view controller inside my test case as follows:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let libraryCollectionVC = storyboard.instantiateViewControllerWithIdentifier("LibraryCollectionViewController") as! LibraryCollectionViewController

And I'm getting the following error:

Could not cast value of type 'MyApp.LibraryCollectionViewController' (0x1010b01f0) to 'MyAppTests.LibraryCollectionViewController' (0x10bd7f580).

So it is clear that it isn't casting, but as I'm still new to Swift, I find myself unable to determine if the error itself is being caused by:

  1. I did something wrong when creating the subclass and I'm referencing a different one (Ergo the MyApp.[vc] vs MyAppTests.[vc])
  2. The casting using as! is incorrect
  3. Any other reason

Any help would be appreciate, thanks in advance.

Update 1: When I was creating the view controller, the last step shows 2 checkboxes under a Target header, I enabled both of them, could that be the cause?

like image 878
Christopher Francisco Avatar asked Apr 23 '15 18:04

Christopher Francisco


2 Answers

My problem was I was referencing NSBundle.mainBundle() from the unit tests whereas I needed to use:

let bundle = Bundle(for: self.classForCoder)
like image 132
BrianHenryIE Avatar answered Oct 07 '22 16:10

BrianHenryIE


This can happen if a class is a member of two targets (maybe two frameworks?) - and your app is somehow referencing one framework while the unit test target is referencing the second target.

So one of the compiled artefacts has a fully-qualified type Framework1.MyClass while the other is Framework2.MyClass - and they're different classes at runtime because they have different namespaces. (Even though both classes are compiled from the same Swift source file)

like image 44
Matthew Avatar answered Oct 07 '22 16:10

Matthew