Swift 如何在同一个 class 中从另一个方法获取变量

Swift How can i get variable from another method in same class


我是 swift 的初学者。 我写了代码和一个问题。 我想从 func A 获取变量 b 但我不知道如何。 获取方式

/*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*/)
    }

}

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


您无法访问 B 中的 ab,因为 abB 处于不同的范围.您不能从另一个函数访问一个函数中声明的局部变量。

要访问它们,您需要将 ab 移动到 B 可以访问的范围。在这种情况下,这可以是扩展的范围:

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)
    }

}

您可以简单地使用类型为 (CGFloat, CGFloat)Tuple 来实现,即

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)
}