-1

I am using xib file to load my view. So I am using loadNibNamed(_:owner:options:) method, this method return type is: [Any]?. As I understand it should return nil if something goes wrong, but when I am trying to load file that does't exist, my application terminates an exception. I thought that if there is no xib file with given name, loadNibNamed will return nil. So my question is: Is there any way to check that xib file exist through guard or if statements without getting exception from application?

So here is my code:

if let view = Bundle.main.loadNibNamed(name,
                                       owner: self,
                                       options: nil)?.first as? UIView {
   return view
}
else {
   fatalError("no file")
}
savmex
  • 311
  • 1
  • 4
  • 8
  • @ShalvaAvanashvili, thanks a lot, it worked. I think I should do better research in existing questions next time... – savmex Jul 18 '19 at 14:48

1 Answers1

2

You need to verify the xib exists before you try to load it.

Example:

func loadXib() -> UIView? {
    guard Bundle.main.path(forResource: "View", ofType: "nib") != nil else {
        // file not exists
        return nil
    }

    if let view = Bundle.main.loadNibNamed("View",
                                           owner: self,
                                           options: nil)?.first as? UIView {
        return view
    }

    return nil
}
Sagi Shmuel
  • 379
  • 1
  • 6