Alternative to override extension method

I want to expand UIViewby adding some functions and overriding them in any subclass UIViewI want. I found in Apple docs that I cannot override extensions (and the compiler will complain) that make any sense. So

I need someone to suggest an alternative way to the following:

extension UIView { 
  func hide() { //do almost nothing } 
}

class myLabel: UILabel { 
  override func hide() { 
    //do work on uilabel that can't be done on imgView
  }
}

class myImageView: UIImageView {
 override func hide() { 
    //do work on imgView that can't be done on uilabel
  }
}

And the reason I want it is because later in my code I will come across the code below and I have many subclasses and I don't want to write too much if-lets, trying to drop viewtomyLabel, myTextView, myImageView... etc

let view = cell.viewWithTag(someTag)
// and I want to write this below without casting
view.hide()

I tried with protocolsand protocol extensions, but I could not do it.

Any thoughts?


Note. func hide()is just an example. My function has more to do. ** Question updated to be clear.

+4
1

:

, - , .

, :

protocol SomeProtocol {
    func hide()
}

, , UIView , , ( ):

class ParentView : UIView, SomeProtocol {
    func hide() {
        print("PARENT")
    }

    func anyOtherMethod() {

    }
}

UIView, ParentView:

class ViewOne : ParentView {
    override func hide() {
        print("VIEW ONE")
    }
}

class ViewTwo : ParentView {
    override func hide() {
        print("VIEW TWO")
    }
}

, :

let view = cell.viewWithTag(someTag)
// and I want to write this below without casting
view.hide()

UIView, , , super

EDIT:

, , hide() , , , UILabel :

class ParentLabel : UILabel, SomeProtocol {
    func hide() {
        print("PARENT LABEL")
    }
}

if let view = cell.viewWithTag(someTag) as? SomeProtocol {
    view.hide() // prints PARENT LABEL
}

UILabel, , , ParentLabel:

class LabelOne : ParentLabel {
    override func hide() {
        print("LABEL ONE")
    }
}
+2

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


All Articles