Rob Rob - 1 month ago 5
Swift Question

Swift: expected declaration error setting "Label" to a string variable

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() {
// Do any additional setup after loading the view, typically from a nib.

override func 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?

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.