Gerard Grundy Gerard Grundy - 2 months ago 15
Swift Question

Could not cast value of type 'UIView' to 'NSArray'

I'm trying to get all the views within a

Nib
with:

let objects = Bundle.main.loadNibNamed("ViewName", owner: self, options: nil)?[0] as! NSArray
let mainView : UIView = objects[0] as! UIView


Though I'm getting this error:


Could not cast value of type 'UIView' (0x108080b40) to 'NSArray'
(0x105173c58).


Thanks in advance for your help.

Answer

loadNibNamed returns array of type [Any]? and your are subscript it using [0], means you are accessing the first object of Array. So just remove [0].

let objects = Bundle.main.loadNibNamed("ViewName", owner: self, options: nil)

Second option you can directly initialized UIView object.

if let mainView : UIView = Bundle.main.loadNibNamed("ViewName", owner: self, options: nil)?[0] as? UIView {...}

Choose which ever solution will solved your error.