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

I want to make a translation app in swift. Can anyone help me?

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

for eg: "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)

当前您正在创建一个包含字符的代码字典。你需要修改这个并提供单词和它的翻译。

例如

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 += " "
}