2016-03-21 56 views
0

我已經創建了英文和西班牙文單詞之間的小翻譯。如果用戶輸入「貓」,它將通過檢查索引號打印「el gato」。我想知道是否有任何方法可以從包含更多單詞的文件中讀取。Swift 2:從文件中讀取

文件1(英文) 文件2(西班牙語)

文件1將檢查 「你好」 文件2 「HOLA」 並打印正確的翻譯

import UIKit 

class translateViewController: UIViewController { 

@IBOutlet weak var translateTextField: UITextField! 
@IBOutlet weak var translateButton: UIButton! 
@IBOutlet weak var translateLabel: UILabel! 

var englishArray: [String] = ["the cat", "the dog", "hello", ] 
var spanishArray: [String] = ["el gato", "el perro", "hola"] 

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


@IBAction func translateButtonTapped(sender: UIButton) { 

    let emptyString = self.translateTextField.text 

    if (emptyString!.isEmpty) { 

     print("please enter a word") 

    } 

    for transIndex in englishArray.indices { 
     if englishArray[transIndex] == emptyString!.lowercaseString { 

      translateLabel.text = "\(spanishArray[transIndex])" 

      print(transIndex) 
      return 

      } 
     } 
    } 
} 

回答

0

編輯:對不起..完全錯過了「迅速」提及。我必須喝醉:s

要麼添加更多的單詞或者如果你想要做文件我不認爲你需要2個文件......如果你存儲的文字如

hello = hola

然後做一些字符串處理來檢查的話=之前,如果匹配,打印字後=

或更簡單的方法是...

ÿ OU可以存儲的話就像

Hello Hola The cat El gato

那麼做到這一點(有些僞代碼)...

while(reader.hasNextline()) 
{ 
    if (reader.readline().Equals(input_word)) // read the first line and check if it matches the input word 
    { 
     System.out.println(reader.readline()); // print translated word which on the next line 
     break; 
    } 
    reader.readline(); // If it doesn't matches then skip the spanish translation on the next line 
} 
0

推薦的方法用於此目的是Localizable.stringsNSLocalizedString()


  • 創建文件Localizable.strings
  • 例如
  • 用鍵/值對填充字符串文件(即使在Swift中,包括分號的語法也是強制性的)。

    "the cat" = "el gato"; 
    "the dog" = "el perro"; 
    "hello" = "hola"; 
    
  • 翻譯詞/表達與NSLocalizedString()

    translateLabel.text = NSLocalizedString(emptyString!.lowercaseString, comment:"") 
    

NSLocalizedString()檢索關鍵the cat

+0

怎麼樣的價值el gato對於那些沒有在數組列表但裏面本地化的話。字符串?它不會僅檢索數組中的單詞值。 @vadian – Miguel

+0

對不起,我不明白。 – vadian

+0

說我有一個數組=「」貓「,」狗「],但在我的localizable.string裏面我有:」hello「=」hola「;當我在textField中輸入「hello」時,它不會檢索translateLabel.text中的值「hello」@vadian – Miguel