Last active
January 31, 2016 03:36
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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