Swift: expected declaration error setting “Label” to a string variable

一曲冷凌霜 提交于 2019-12-29 07:37:34

问题


I am managing different languages, in a small single pane app, using a different string array for each comment, indexed by an integer variable "userLang", then setting label.text = array[index]. The basic code is:

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

I keep getting an "Expected Declaration" error. I have tried using a simple string in quotes (instead of the array) as a test, and still get the same error. I have searched the web & not found any suggestions that resolve the problem. I tried changing the name if the label, in case I was using "reserved" references.

I searched Apple's developer manual for Swift & can't find the proper syntax for labels. This syntax has worked in other projects, so I am not sure what is going on. I even tried copy/pasting relevant sections to a new project (one of the online suggestions, in case of Xcode bug), with no better results. I have noticed small differences (a space or capital) can make a big difference in Swift. Is there something I am doing wrong here? Any suggestions?


回答1:


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

These are not declarations, you will need to move them to viewDidLoad() or some other appropriate place. Your syntax for labels is fine, but you have the code in the wrong place in the class.



来源:https://stackoverflow.com/questions/26764266/swift-expected-declaration-error-setting-label-to-a-string-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!