Swift-无法访问结构属性

问题描述 投票:0回答:1

学习迅速,但对以下内容有些困惑。我已经创建并实例化了struct,但是除非该struct位于我的类方法中,否则无法访问其视图控制器类内部struct的属性。见下文,为什么会这样?

class WeatherViewController: UIViewController, UITextFieldDelegate, WeatherManagerDelegate {



    //create new weather manager struct
    var weatherManager = WeatherManager()

    //can't access property here, but I can access it inside of functions within this
    //class, see below under viewDidLoad()
     weatherManager.delegate = self

    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var searchTextField: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()


        //can access property here
        weatherManager.delegate = self

    }
swift structure
1个回答
2
投票

问题不是在声明和创建WeatherManager对象的地方。问题是这一行:

weatherManager.delegate = self

command(技术上是statement),而不是声明。 (它上面的行声明,恰好同时设置了weatherManager属性的默认值)。在C ++ / Java系列的大多数语言中,这是一条相当普遍的规则-请参见下面的简短C ++示例。命令(语句)必须位于某个方法(或非OOP编程中的函数)内部,而不位于文件或类的顶层。在Swift中,设置对象的委托之类的操作通常会在视图控制器的viewDidLoad中进行。


int x = 0;  // legal: declaring a global variable                               

x = x + 42; // NOT legal: this is a statement, not a declaraiton                

int main()
{
  x = x + 42; // legal: now we're inside a function                             
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.