Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

variables - Swift 4.2 Setter Getter, All paths through this function will call itself

With swift 4.2 I have begun to see a lot of issues, and one of them i'm not really sure how to resolve, since my getter method should be returning the value itself.

I imagine what is happening is that the getter will attempt to access the getter when calling self.type

How can i resolve this issue?

Here is a screenshot of the code with the error.

enter image description here

Thanks in advance

Here is the written code

@objc var type: DecisionType {
    set {
        if(newValue == DecisionType.DecisionDouble){
            //Yes button and NO button should be showing
            okButton.isHidden = true;
            yesButton.isHidden = false;
            noButton.isHidden = false;
        }
        else {
            //Only Ok button should be showing
            okButton.isHidden = false;
            yesButton.isHidden = true;
            noButton.isHidden = true;
        }
    }
    get {
        return self.type;
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your issue is that there is no stored property type for the getter to return. type is a computed property. When you try to read its value, it calls the getter you defined. This getter calls the getter, which in turn calls the getter which calls the getter... and so on. You have infinite recursion.

Most likely, what you meant to do is have a stored property, that just has some fancy behaviour whenever its set. Rather than using a computed property with a custom get and set, use a stored property with a willSet or didSet block:

@objc var type: DecisionType {
    didSet {
        let isDecisionDouble = newValue == DecisionType.DecisionDouble

        okButton.isHidden = isDecisionDouble;
        yesButton.isHidden = !isDecisionDouble;
        noButton.isHidden = !isDecisionDouble;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...