Skip to content

Instantly share code, notes, and snippets.

@miguelfermin
Last active January 31, 2016 03:36
Show Gist options
  • Save miguelfermin/55e3d7de4716f7fdef0e to your computer and use it in GitHub Desktop.
Save miguelfermin/55e3d7de4716f7fdef0e to your computer and use it in GitHub Desktop.
A simple function that reverses a string. It demonstrates the use of "inout" variables and Array's "reduce" method. The use of "inout" here also demonstrates that you can still use value types in place of reference types without loosing the ability to have functions updating the actual variable values.
func reverseString(inout string: String) {
var chars = Array(string.characters)
var temp: Character!
for i in 0..<chars.count/2 {
temp = chars[i]
chars[i] = chars[chars.count - (i + 1)]
chars[chars.count - (i + 1)] = temp
}
string = chars.reduce("") {$0 + "\($1)"}
}
var name = "Hello World"
reverseString(&name)
print(name)
// prints "dlroW olleH"
// A more concise version using the built-in reverse() method
func reverseString(inout string: String) {
string = string.characters.reverse().reduce("") {$0 + "\($1)"}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment