小编典典

Swift:预期的声明错误将“ Label”设置为字符串变量

swift

我正在一个小型的单窗格应用程序中管理不同的语言,为每个注释使用不同的字符串数组,并由整数变量“ userLang”索引,然后设置label.text =
array [index]。基本代码是:

import UIKit
class ViewController: UIViewController {
   var userLang = 0
   var arrayOne = ["hi", "hola"]
   var arrayTwo = ["Bye", "Adios"]
   @IBOutlet weak var msgArrayOne: UILabel!
   @IBOutlet weak var msgArrayTwo: UILabel!

   msgArrayOne.text = arrayOne[userLang]  //Error here: !Expected declaration
   msgArrayTwo.text = arrayTwo[userLang]  //odd, but this line gets no error until I 
                                          //remove the first line above, then 
                                          //this line gets the same error.

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

   override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
   }
 }

我不断收到“期望的声明”错误。我曾尝试在引号(而不是数组)中使用简单的字符串作为测试,但仍然遇到相同的错误。我已经在网上搜索过,却没有找到解决问题的任何建议。如果我使用的是“保留”引用,我尝试更改标签名称。

我在Apple的开发人员手册中搜索了Swift,但找不到适合标签的语法。此语法已在其他项目中使用,所以我不确定发生了什么。我什至尝试将相关部分复制/粘贴到一个新项目中(在线建议之一,以防Xcode错误),但没有更好的结果。我已经注意到,Swift中的微小差异(空格或大写字母)可以产生很大的差异。我在这里做错什么了吗?有什么建议?


阅读 227

收藏
2020-07-07

共1个答案

小编典典

msgArrayOne.text = arrayOne[userLang]  
msgArrayTwo.text = arrayTwo[userLang]

这些不是声明,您需要将它们移至viewDidLoad()或其他适当的位置。标签的语法很好,但是代码在类中的位置错误。

2020-07-07