Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. // If you want to create some common way to load objects from nibs, you will probably try something like that:
  2. protocol NibLoadable: class {
  3. static func fromNib() -> Self?
  4. static func nibName() -> String
  5. }
  6.  
  7. extension NibLoadable {
  8. static func nibName() -> String {
  9. return String(describing: Self.self)
  10. }
  11.  
  12. static func fromNib() -> Self? {
  13. let nibContent = Bundle(for: Self.self).loadNibNamed(nibName(), owner: nil, options: nil)
  14. return nibContent?.first { $0 is Self } as? Self
  15. }
  16. }
  17.  
  18. extension UIView: NibLoadable { }
  19.  
  20. // But oups!
  21. // Method 'fromNib()' in non-final class 'UIView' must return `Self` to conform to protocol 'NibLoadable'
  22. // So what happend?
  23. // UIView and all of its subclasses are adopting the NibLoadable protocol. It means, for UIView, that there will be
  24. // method static func fromNib() -> UIView?
  25. // Every UIView's subclasses will inherit this method, but protocol confirmance inherited too and expect
  26. // static func fromNib() -> ChildView? method. So any subclass will violate protocol confirmance.
  27.  
  28. // So, should I create this function by hands for every class I want to load from nib?
  29. // No! Here another generic solution, but not so elegant as protocol with default implementation:
  30.  
  31. func loadFromNib<T: AnyObject>(named nibName: String = String(describing: T.self)) -> T? {
  32. let nibContent = Bundle(for: T.self).loadNibNamed(nibName, owner: nil, options: nil)
  33. return nibContent?.first { $0 is T } as? T
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement