This code introduces the caesar() method. It accepts a String and a "shift" Int. And it returns a String.
func caesar(value: String, shift: Int) -> String {
// Empty character array.
var result = [Character]()
// Loop over utf8 values.
for u in value.utf8 {
// Apply shift to UInt8.
let s = Int(u) + shift
// See if value exceeds Z.
// ... The Z is 26 past "A" which is 97.
// ... If greater than "Z," shift backwards 26.
// ... If less than "A," shift forward 26.
if s > 97 + 25 {
result.append(Character(UnicodeScalar(s - 26)!))
} else if s < 97 {
result.append(Character(UnicodeScalar(s + 26)!))
} else {
result.append(Character(UnicodeScalar(s)!))
}
}
// Return String from array.
return String(result)
}
// Test Caesar cipher on this string.
let value1 =
"test"
print(value1)
let value2 = caesar(value: value1, shift: 18)
let value3 = caesar(value: value2, shift: -18)
print(
"\(value2) \(value3)")
let value4 = caesar(value: value1, shift: 1)
let value5 = caesar(value: value4, shift: -1)
print(
"\(value4) \(value5)")
let value6 =
"exxegoexsrgi"
let value7 = caesar(value: value6, shift: -4)
print(
"\(value6) \(value7)")
test
lwkl test
uftu test
exxegoexsrgi attackatonce