Skip to content

Instantly share code, notes, and snippets.

@jeremy-w
Created August 4, 2014 21:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jeremy-w/2c638619ba302dea6b8a to your computer and use it in GitHub Desktop.
Save jeremy-w/2c638619ba302dea6b8a to your computer and use it in GitHub Desktop.
Demonstrates rot13 in Swift with non-[A-Z][a-z] pass-through.
import Cocoa
var input = "This is a test"
var expected = "Guvf vf n grfg"
/// Advances `i` by `by` through `string`, wrapping to start on hitting
/// end.
/// NOTE: `by` must be non-negative.
func wrappingAdvance(string: String, i: String.Index, by: Int)
-> String.Index {
assert(by > 0)
var left = by
var j = i
let s = string.startIndex
let e = string.endIndex
while left > 0 {
j = j.successor()
if j == e {
j = s
}
left -= 1
}
return j
}
/// Returns the string with A-Za-z rotated.
func rot13(text: String) -> String {
let uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let lowercase = uppercase.lowercaseString
let count: Int = countElements(uppercase)
let rotation = count / 2
assert(countElements(lowercase) == count)
var output = ""
for ch in text {
if let i = find(uppercase, ch) {
let rotated = wrappingAdvance(uppercase, i, rotation)
output += uppercase[rotated]
} else if let i = find(lowercase, ch) {
let rotated = wrappingAdvance(lowercase, i, rotation)
output += lowercase[rotated]
} else {
output += ch
}
}
return output
}
rot13(input) == expected
"été" == rot13(rot13("été"))
@jeremy-w
Copy link
Author

jeremy-w commented Aug 4, 2014

Comments on the initial version:

  • Mess with wrappingAdvance suggests that a String is likely the wrong datatype for the uppercase and lowercase data. Likely conflating an array with a string here.
  • The if branches in the iteration are very redundant and need DRYing.

@shepting
Copy link

shepting commented Aug 9, 2014

Here's another go, a little shorter but less elegant: https://gist.github.com/shepting/bdeab98418410fdeedc9

@shepting
Copy link

shepting commented Aug 9, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment