ios swift 编译器显示预期的声明错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31873673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:11:08  来源:igfitidea点击:

swift compiler shows Expected declaration error?

iosxcodeswift

提问by Ashwini

When this code is written in AllListViewControllerand run, the compiler shows the Expected Declaration error:

当这段代码被写入AllListViewController并运行时,编译器显示预期声明错误:

for list in lists{
    let item = ChecklistItems()
    item.text = "Item for \(list.name))"
    list.items.append(item)
}       

回答by Dharmesh Kheni

I think you have the code in the wrong place in the class same like thisquestion.

我认为您的代码在类中的错误位置与问题相同。

so move it to any function or in viewDidLoadmethod.

所以将它移动到任何函数或viewDidLoad方法中。

Hope it will help.

希望它会有所帮助。

回答by TheTiger

You have the code like below image:

你有如下图所示的代码:

enter image description hereSeems like Your code is outside the function. If allListViewControlleris your UIViewControllerclass where the forloop code is written make sure the code should be inside the body of any function of allListViewControllerclass. It can not be outside.

在此处输入图片说明好像你的代码在函数之外。如果allListViewController是您编写循环代码的UIViewController类,请for确保代码应位于allListViewController类的任何函数的主体内。它不能在外面。

Example:

例子:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for list in lists{
        let item = ChecklistItems()
        item.text = "Item for (list.name))"
        list.items.append(item)
    }
}

You can just initialise/declarethe variables (will be global variables)outside the function body.

您可以在函数体之外初始化/声明变量(将是全局变量)