Tel Tel - 5 months ago 34
Swift Question

How to implement a ROT13 function in Swift?

I would like to create a function that receives a String and returns a String, and that replaces a letter with the letter 13 letters after it in the alphabet (ROT13). I found a lot of examples, unfortunately I was not able to make it work no one because of various errors. For example this one:

var key = [String:String]() // EDITED
let uppercase = Array(arrayLiteral: "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
let lowercase = Array(arrayLiteral: "abcdefghijklmnopqrstuvwxyz")
for i in 0 ..< 26 {
key[uppercase[i]] = uppercase[(i + 13) % 26]
key[lowercase[i]] = lowercase[(i + 13) % 26]
}

func rot13(s: String) -> String {
return String(map(s, { key[$0] ?? $0 }))
}

Answer

Actually your initial approach of mapping Characters was good:

var key = [Character: Character]()

But the two arrays must the be arrays of Characters:

let uppercase = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)
let lowercase = Array("abcdefghijklmnopqrstuvwxyz".characters)

(Remark: You (almost) never want to call a xxxLiteral: initializer explicitly. Doing so is (almost) always hiding the actual problem.)

Now your code to fill the dictionary works:

for i in 0 ..< 26 {
    key[uppercase[i]] = uppercase[(i + 13) % 26]
    key[lowercase[i]] = lowercase[(i + 13) % 26]
}

And transforming a string can be done as

//                       map
// String --> Characters ---> Characters -> String

func rot13(s: String) -> String {
    return String(s.characters.map { key[$0] ?? $0 })
}
Comments