Can I use Quick Generic in this case?

I want to add saved properties to a subclass of UIView, e.g. UIView , UIImageView , UIPickerView , etc.,

I need to create instances of UIView only from a subclass. Subclasses differ only in type, all properties and methods are the same. The type also conforms to several protocols.

class View: UIView, UIGestureRecognizerDelegate, ProtocolDelegate2 { var property1 = CGRectZero var property2:Int = 0 var property3 = false func configView(config: [String:AnyObject]) { let recognizer = UIPanGestureRecognizer(target: self , action: Selector("panGestureHandler:")) recognizer.delegate = self addGestureRecognizer(recognizer) } func panGestureHandler(gestureRecognizer:UIPanGestureRecognizer) { } } class ImageView: UIImageView, UIGestureRecognizerDelegate, ProtocolDelegate2 { var property1 = CGRectZero var property2:Int = 0 var property3 = false func configView(config: [String:AnyObject]) { let recognizer = UIPanGestureRecognizer(target: self , action: Selector("panGestureHandler:")) recognizer.delegate = self addGestureRecognizer(recognizer) } func panGestureHandler(gestureRecognizer:UIPanGestureRecognizer) { } } class PickerView: UIPickerView, UIGestureRecognizerDelegate, ProtocolDelegate2 { var property1 = CGRectZero var property2:Int = 0 var property3 = false func configView(config: [String:AnyObject]) { let recognizer = UIPanGestureRecognizer(target: self , action: Selector("panGestureHandler:")) recognizer.delegate = self addGestureRecognizer(recognizer) } func panGestureHandler(gestureRecognizer:UIPanGestureRecognizer) { } } 

Using:

 let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) let imageView = ImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) let pickerView = PickerView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) view.configView(config: JsonData) view.alpha = 0.5 imageView.configView(config: JsonData) imageView.alpha = 0.2 pickerView.configView(config: JsonData) pickerView.backgroundColor = UIColor.orangeColor() 

Now the question is: can we use Swift Generics in this case, since classes differ only in types. Or there is a better design for better code maintenance.

+1
source share
1 answer

Generics will not help you if your class should be a subclass of UIView . If you try to do this:

 class A<T: UIView> : T { // ERROR var prop: String? } 

the compiler complains that T must be a type or protocol.

You can do it:

 class A<T: UIView> { var theView: T var prop: String? } 

But this is no better than just using inheritance:

 class A { var theView: UIView! var prop: String? init(view: UIView) { theView = view } } 
+1
source

Source: https://habr.com/ru/post/1212354/


All Articles