iOS Question

How to create generic swift function that can work for 2 different classes?

In my two classes, I have the following code

// Two classes who's code I am trying to reduce using protocols
class class1 {
var view: viewSubclass1!
func printName() {
print("This is the view: \(view)")
}
}

class class2 {
var view: viewSubclass2!
func printName() {
print("This is the view: \(view)")
}
}

// The protocol and protocol extension I am trying to create
protocol myProtocol {
var view: UIView {get set}
func printName()
}

extension myProtocol {
func printName() {
print("This is the view: \(view)")
}
}

// The subviews of UIView
class viewSubclass1: UIView {}
class viewSubclass2: UIView {}


As you can see,
class1
and
class2
are different classes, but have the same variable name:
view
and the same function names. The difference is that the
view
variable are of different types.

Question: Using protocols and protocol-extensions, how can I reduce the code between the two classes? I would not want to do repeat code because they are so similar. I have been trying different variations of the code, but I keep getting stuck. I do not understand it well. How can i get both classes to use the same code using a protocol, and a protocol extension?

Answer

(Updated)

With declaring the protocol and protocol extension:

protocol MyProtocol {
    associatedtype BaseView: UIView
    var view: BaseView! {get set}
    func printName()
}

extension MyProtocol {
    func printName() {
        print("This is the view: \(view)")
    }
}

And given two subclasses of UIView:

class ViewSubclass1: UIView {}
class ViewSubclass2: UIView {}

(Capitalized some type names for readability.)

And declaring two classes like this:

class Class1: MyProtocol {
    var view: ViewSubclass1!
}

class Class2: MyProtocol {
    var view: ViewSubclass2!
}

You'll find you can use your printName() for both Class1 and Class2.

One thing important here:

If you declare your view in the protocol as var view: UIView {get set}, var view: ViewSubclass1! cannot fulfill the requirement for the protocol. (One thing is the difference of optionality, another is that you cannot assign any instances of UIView or UIView's subclasses to view: ViewSubclass1.)

But many things depend on what you really want to do in your common code.

Comments