Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Extension, All paths through this function will call itself [duplicate]

Tags:

ios

swift

I have a warning that I can not delete

All paths through this function will call itself

My code:

extension UIView {

    var isLowAlpha: Bool {
        get {
            return self.isLowAlpha
        }
        set {
            self.isUserInteractionEnabled = !newValue
            self.alpha = newValue ? 0.3 : 1
        }
    }

}

I can not modify the code with this, because I have an error extension must not contain stored property ..:

extension UIView {

    var isLowAlpha: Bool {
        didSet {
            self.isUserInteractionEnabled = !isLowAlpha
            self.alpha = isLowAlpha ? 0.3 : 1
        }
    }

}

What is the solution?

like image 673
Mickael Belhassen Avatar asked Jan 22 '26 22:01

Mickael Belhassen


2 Answers

One possible solution is to revert the process:

var isLowAlpha: Bool {
    get {
        return !isUserInteractionEnabled
    }
    set {
        isUserInteractionEnabled = !newValue
        alpha = newValue ? 0.3 : 1
    }
}

or better, since you are not interested in the getter, make it a function:

func setIsLowAlpha(_ lowAlpha: Bool) {
    self.isUserInteractionEnabled = !lowAlpha
    self.lowAlpha = newValue ? 0.3 : 1
}

Anyway, looking at your code, you probably want to implement that a view is disabled. That's usually a task for UIControl subclasses, not UIView.

Also note the same can be implemented using a wrapper view:

class AlphaView: UIView {
   var isLowAlpha: Bool = false {
      didSet {
         isUserInteractionEnabled = !isLowAlpha
         alpha = isLowAlpha ? 0.3 : 1
      }
   }
}

And put your views inside.

like image 103
Sulthan Avatar answered Jan 25 '26 12:01

Sulthan


In the first case you were recursively calling the variable's getter so it would never return. The way to fix this would be with a stored property _isLowAlpha, but unfortunately, as the second error mentions, Swift extensions cannot contain stored variables; they can only contain computed properties. If you really needed to add another property you would need to instead subclass UIView instead of making an extension.

However, in this case you can kind of cheat as long as you are not setting the UIView's alpha property elsewhere by directly using the alpha property:

extension UIView {
    var isLowAlpha: Bool {
        get {
            return self.alpha == 0.3;
        }
        set {
            self.alpha = newValue ? 0.3: 1
            self.isUserInteractionEnabled = !newValue
        }
    }
}
like image 28
BradzTech Avatar answered Jan 25 '26 13:01

BradzTech