swift - 如何从方法内部更新类变量,以便该变量对 Swift 中的其他类可见?

标签 swift function variables

// some VC
Class FirstClass: UIViewController {

    var tag = -1 // supposed to represent a tag for a UIView inside of FirstClass

        // supposed to change the tag 
        func abc() {

            tag = 5

        }


        // returns the tag
        func getTag() -> Int {

            return tag

       }
    }


// another VC
Class SecondClass: UIViewController {

    FirstClass().abc()
    var a = FirstClass().getTag() // prints -1; I want it to print 5
    let someView = view.viewWithTag(a) as! UIView // nil

}

我想从函数内部更新“tag”变量。为了简单起见,我省略了一些基本函数,例如“viewDidLoad”。 谢谢!

最佳答案

像这样更改 SecondClass 中的代码:

Class SecondClass: UIViewController {

      let myfirstClass = FirstClass()
      myFirstClass.abc()     // changes the tag in your instance of FirstClass

      var a = myfirstClass.getTag()

      // will print 5 because now you ask the instance, 
      // where the abc-function was called       
}

关于swift - 如何从方法内部更新类变量,以便该变量对 Swift 中的其他类可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760874/

相关文章:

ios - 创建 http post 请求时我得到 0 字节

ios - 有没有办法使用 AVAudioPlayerNode 从头开始​​重播声音?

actionscript-3 - 引用由 Actionscript 3 中的子类定义的函数

C数独回溯求解器预检函数

java - 数学操作后的变量类型

swift - 如何在 Xcode 中添加可由 Swift 包管理器运行的可执行文件?

java - android按值传递?

powershell - 在Powershell中使用子脚本修改父脚本中的变量

javascript - 动态选择变量

ios - Swift,使用函数 UIView.removeFromSuperview 作为 forEach 函数中 View 数组的参数