Dr.Ax Dr.Ax - 6 months ago 23
Swift Question

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

I'm developing an app for translating word to word from English to my local dialect. Since there are no existing translation services for my dialect, I have to create a dictionary of words for each English word and return the local word for it. Here is sample code I found. But this code is for ecoding character by charcter instead of word by word translation. Can someone help me with a code to translate each word?


for eg: "apple = aaple"


Here is the sample code.

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)

Answer

Currently you are creating a code dictionary with characters. You need to modify this and provide word and it's translation.

For e.g.

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

Now, you need to split the input string into individual words. You can do this using split

Complete code

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