Reputation: 169
Inside a class, I want to add a variable of type UIView, which conforms to the following protocol:
public protocol Shadow: UIView {
func applyShadow()
}
public extension Shadow {
func applyShadow() {
self.layer.cornerRadius = 16
...
}
}
To then be able to do something like this :
private lazy var shadowView: Shadow = UIView()
shadowView.applyShadow()
I want to do this, so I don't have to bring that function applyShadow()
to my class and have repeated code.
Upvotes: 0
Views: 436
Reputation: 295
Basically, there are 2 ways to do this. One is having a protocol Shadow
then creating a concrete class to conform to Shadow
protocol as below
public protocol Shadow: UIView {
func applyShadow()
}
public extension Shadow {
func applyShadow() {
self.layer.cornerRadius = 16
}
}
// re-use Shadow protocol
//this is a concrete class that conforms to Shadow protocol
class Title: UIView, Shadow {}
class Card: UIView {
private lazy var oneVariable: Title = {
let view = Title()
view.applyShadow()
return view
}()
}
Or you can create an extension of UIView in Shadow
class
class Shadow: UIView {}
extension UIView {
func applyShadow() {
self.layer.cornerRadius = 16
}
}
Upvotes: 2