Here is a Demo to show you a good use of generics

Let’s say we have a requirement to make an automatic scroll view and let’s say it’s a custom VScrollView class

Then the product wanted to make another scroll view:

A common solution we use in OC is to encapsulate a UIVIew with a specific UI layout inside it as a class and pass it in to a View that supports scrolling.

OC does not use generic writing: here is the pseudocode

Class VScrollView: UIView {var topView: UIView var bottomView: UIView func configBaseUI() {// Add topView and bottomView. } func scroll() {// View up}} /// the first GIF in orange left image of the right text view class YellowItemView: VScrollView = vScrollView () vscrollView.topView = YellowItemView() UIView {/// internal layout code omitted} Vscrollview.bottomview = YellowItemView() vscrollView.configBaseui () // Start to scroll the view vscrollView.scroll () /// grey in the second GIF GrayItemView: UIView {GrayItemView: UIView {GrayItemView: UIView {GrayItemView: UIView {GrayItemView: UIView}Copy the code

In Swift we can use generics to unify the two views and only consider the specific type when calling them.

class VScrollView<T: UIView>: UIView { var topView: T var bottomView: T override init(frame: CGRect) {super.init(frame:.zero) configBaseUI()} func configBaseUI() {// Add topView and bottomView. AddSubView (topView) addSubView(bottomView)} func Scroll () {// Scroll up} GymNewMarqueeView<YellowItemView>() yellowVScrollView.scroll() let grayVScrollView = GymNewMarqueeView<GrayItemView>() yellowVScrollView.scroll()Copy the code

Demo only explains how generics simplify and encapsulate reusable views. The syntax and code depend on the actual project.

If you want to unify the data configuration methods, you can use the protocol to achieve this.