我想在swift中制作一个翻译应用程序。谁能帮我?

时间:2016-05-11 05:01:34

标签: ios swift translation

我正在开发一个应用程序,用于将单词从英语翻译成我当地的方言。由于我的方言没有现有的翻译服务,我必须为每个英语单词创建一个单词词典,并为其返回本地单词。这是我找到的示例代码。但是这段代码用于通过字符而不是逐字翻译来识别字符。有人可以用我的代码来帮助我翻译每个单词吗?

  

例如:" apple = aaple"

以下是示例代码。

var code = [
    "a" : "b",
    "b" : "c",
    "c" : "d",
    "d" : "e",
    "e" : "f",
    "f" : "g",
    "g" : "h",
    "h" : "i",
    "i" : "j",
    "j" : "k",
    "k" : "l",
    "l" : "m",
    "m" : "n",
    "n" : "o",
    "o" : "p",
    "p" : "q",
    "q" : "r",
    "r" : "s",
    "s" : "t",
    "t" : "u",
    "u" : "v",
    "v" : "w",
    "w" : "x",
    "x" : "y",
    "y" : "z",
    "z" : "a"
]

var message = "hello world"
var encodedMessage = ""

for char in message.characters {
    var character = "\(char)"

    if let encodedChar = code[character] {
        // letter
        encodedMessage += encodedChar
    } else {
        // space
        encodedMessage += character
    }
}

print(encodedMessage)

1 个答案:

答案 0 :(得分:2)

目前,您正在创建包含字符的代码字典。你需要修改它并提供单词及其翻译。

例如

var code = [
    "hello" : "halo",
    "world" : "earth",
    "apple" : "aapl"
    //Add more translations here
]

现在,您需要将输入字符串拆分为单个单词。您可以使用split

执行此操作

完整代码

var code = [
    "hello" : "halo",
    "world" : "earth",
    "apple" : "aapl"
    //Add more translations here
]

let message = "hello world"

var encodedMessage = ""

//Split message String into words seperated by space(" ")
let array = message.characters.split(" ")

for singleWord in array {

    let word = String(singleWord)
    if let encodedWord = code[word] {
        // word
        encodedMessage += encodedWord
    } else {
        // word not found in the map
        encodedMessage += word
    }
    // seperate each word with a space
    encodedMessage += " "
}