Search code examples
swiftclassprotocolsextension-methods

Two classes to use the same function to create custom view - Swift


I am kind of new to Swift and I can't figure this out. I have two classes where I need to use the same function to set up a custom UIStackVIew (Rating Control that shows rating stars). Each class has a variable called value that needs to be passed inside the function. I don't want to be duplicating the same code of the setUpStackView function inside each class. I have the following code:

class Class1: UIStackView {

    var variable1 = "value1"

    override init(frame: CGRect){
      super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder){
      super.init(coder: aDecoder)
    }

    setUpStackView(value: variable1)

}

class Class2: UIStackView {

    var variable2 = "value2"

    override init(frame: CGRect){
      super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder){
      super.init(coder: aDecoder)
    }

    setUpStackView(value: variable2)

}




extension Class1 {

  func setUpStackView(value: String){
    //code to set UIStackView rating control and to use the variable value
  }

}

How can I implement the extension for the Class2? I am stuck with this. Any help would be greatly appreciated!


Solution

  • One solution can be moved common code to protocol where you can abstract out:

    protocol  BaseStackView {
        var variable :String { get set }
    }
    
    class Class1: UIStackView,BaseStackView {
    
    
    
        var variable = "value1"
    
        override init(frame: CGRect){
          super.init(frame: frame)
            self.setUpStackView(value: variable)
    
        }
    
        required init(coder: NSCoder) {
            super.init(coder: coder)
            self.setUpStackView(value: variable)
        }
    }
    
    class Class2: UIStackView,BaseStackView {
    
        var variable = "value2"
    
        override init(frame: CGRect){
          super.init(frame: frame)
            self.setUpStackView(value: variable)
        }
    
        required init(coder: NSCoder) {
            super.init(coder: coder)
            self.setUpStackView(value: variable)
        }
    
    
    
    }
    
    
    
    extension UIStackView {
        func setUpStackView(value: String) {
            //Your setup here
        }
    }