Generic IBDesginables UIView Extension

I would like to create a universal extension for a class in order to add some constructive ability to any subclass of UIView and thereby not add functionality to all subclasses. So, it would be nice to add an extension for UIView that conforms to the SomeProtocol protocol (it is empty because it is just a tag to mark the classes that I want to add to the functionality). Then just add this protocol to any subclass of UIView where I want this functionality to be implemented as follows:

protocol SomeProtocol { //empty } class BCBorderedView : UIView, SomeProtocol { //empty } class BCBorderedSearch: UISearchBar, SomeProtocol { //empty } 

My implementation below receives an error message with the message

"Trailing 'where' clause for extending non-generic type 'UIView'"

 @IBDesignable extension UIView where Self:SomeProtocol //Error: Trailing 'where' clause for extension of non-generic type 'UIView' { @IBInspectable public var cornerRadius: CGFloat { set (radius) { self.layer.cornerRadius = radius self.layer.masksToBounds = radius > 0 } get { return self.layer.cornerRadius } } @IBInspectable public var borderWidth: CGFloat { set (borderWidth) { self.layer.borderWidth = borderWidth } get { return self.layer.borderWidth } } @IBInspectable public var borderColor:UIColor? { set (color) { self.layer.borderColor = color?.cgColor } get { if let color = self.layer.borderColor { return UIColor(cgColor: color) } else { return nil } } } } 

Removing a sentence where it compiles and works, but it adds functionality to all UIView and its subclasses (basically, all user interface elements), due to which the IB agent falls into the storyboard from time to time.

Any ideas on how this plan can be updated to work?

+1
generics ios swift3 swift-extensions ibdesignable
Jun 22 '17 at 17:09 on
source share
1 answer

extension Foo where ... can only be used if Foo

  • general class or structure
  • protocol containing some related types
  • a protocol in which we extend the default implementation when Self has a specific (object / reference) type or matches some types.

Where clause for a non-generic UIView extension

It follows from the above error that UIView is not a generic class type, so the where clause cannot be applied here.

So, instead of trying to extend UIView , you should extend SomeProtocol with the default implementation for cases where Self: UIView

Your extension should extend functionality for all types that match SomeProtocol and are of type UIView

In short, you should switch the order in the extension clause. So,

 extension UIView where Self : SomeProtocol 

it should be

 extension SomeProtocol where Self: UIView 
+1
Jun 22 '17 at 21:57
source share



All Articles