Homework Problem: When the program tried to encrypt the "y" in ["c", "o", "d", "e", "c", "a", "d", "e", "m", "y"], it found its index in the alphabet, 24.
But when it looked up the letter 3 spaces to the right, which would be alphabet[27], it threw an error because the alphabet only has 26 elements! It is “out of range”.
To fix this, we can “wrap around” the alphabet by using the remainder operator: %.
On the line where we replace the current character in message, change alphabet[j+3] to alphabet[(j+3) % 26].
Now the new letter position will never go beyond 26.
Code:
var alphabet: [Character] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
var secretMessage = "codecademy"
var message = Array(secretMessage)
for h in 0..<message.count{
for a in 0..<alphabet.count{
if message[h] == alphabet[a]{
message[h] = alphabet[(a+3)%26]
break
}
}
}