2014-11-05 65 views
8

我管理不同的語言,在一個小的單窗格應用程序,使用不同的字符串數組爲每個評論,索引整型變量「userLang」,然後設置標籤.text = array [index]。基本代碼是:Swift:預期的聲明錯誤設置「標籤」爲一個字符串變量

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 bug的情況下),沒有更好的結果。我注意到小的差異(空間或資本)可以在Swift中產生很大的差異。有什麼我在這裏做錯了嗎?有什麼建議麼?

回答

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

這些不是聲明,您需要將它們移動到viewDidLoad()或其他適當的位置。您的標籤語法很好,但是您的代碼在類中錯誤的位置。

+1

謝謝!你說的話很直觀。設置標籤字段是分配,而不是聲明,需要成爲動作/功能的一部分。暫時,我添加了一個按鈕,將其作爲一個動作拖入代碼中,將所有標籤分配放入其中,並且錯誤消失 - 代碼成功編譯。最終,我會把它放在一個選擇器視圖中,但我仍然在學習這個語法(有點複雜)。 – Rob 2014-11-05 22:29:44