Swift extend UIView to return calling type

Viewed 75

I want to extend base class (UIView) where I work on that object and return the calling object with correct type

extension UIView {
    func withCleanBg() -> UIView {
        self.backgroundColor = .clear
        return self;
    }
}

For example if I call let btn:UIButton = UIButton().withCleanBg() I want the btn to stay UIButton after calling the extension and not to get UpCasted.

I want this to chain function calls like UIButton().withCleanBg().withFillInParent() and so on

2 Answers

Return Self as the type:

func withCleanBg() -> Self {

You can return Self and use @discardableResult attribute so no need to care about the return. For more about @discardableResult

extension UIView {
    @discardableResult
    func withCleanBg() -> Self {
        self.backgroundColor = .clear
        return self
    }
    
    @discardableResult
    func withThemeCorner() -> Self {
        self.layer.cornerRadius = 10
        return self
    }
    
    @discardableResult
    func withFillInParent() -> Self {
        // Do your code here
        return self
    }
}

Example:

UIButton().withCleanBg().withFillInParent() // Now this will not give warning like "Result of call to 'withFillInParent()' is unused"
Related