0


I'm a beginner of swift. I wrote code and one question. I want to get variable b from func A but I don't know how. How to get it.

/*This is extension from FirstViewController*/
extension FirstViewController{

    private func A() {
        let a:CGFloat  = view.frame.size.width
        let b:CGFloat  = view.frame.size.height
    }

    private func B() {
        self.Something.frame.size = CGSize(width: /*I want to get a in here*/, height: /*I want to get b in here*/)
    }

}
0

2 Answers 2

1

You can simply use a Tuple of type (CGFloat, CGFloat) to achieve that, i.e.

private func A() -> (a: CGFloat, b: CGFloat)
{
    let a:CGFloat  = view.frame.size.width
    let b:CGFloat  = view.frame.size.height
    return (a, b)
}

private func B()
{
    self.Something.frame.size = CGSize(width: self.A().a, height: self.A().b)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much :) I solved my problem!! Your way is also wonderful
Sure..Happy coding,,:)
0

Note that the actual solution to your problem depends highly on what you actually want to do (your ultimate goal).


You can't access a or b in B because a and b are in a different scope from B. You can't access local variables declared in a function from another function.

To access them, you need to move a and b to a scope that is accessible by B. In this case, this can be the scope of the extension:

extension FirstViewController{
    var a: CGFloat { return view.frame.size.width }
    var b: CGFloat { return view.frame.size.height }
    private func A() {

    }

    private func B() {
        self.Something.frame.size = CGSize(width: a, height: b)
    }

}

1 Comment

Thank you so much :) I solved my problem!! Your code is very simple and minimal!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.