Reversing the order of a string value
Note: If you don't want to use the reversed()
in-built function, then you can use the following code.
One-liner using Higher-order function "Reduce" on the string.
extension String {
func reverse() -> String { return self.reduce("") { "\($1)" + $0 } }
}
In swift 4.0, directly call reversed
on a string will get the job done
let str = "abc"
String(str.reversed()) // This will give you cba
Commented inline,
func reverse(_ s: String) -> String {
var str = ""
//.characters gives the character view of the string passed. You can think of it as array of characters.
for character in s.characters {
str = "\(character)" + str
//This will help you understand the logic.
//!+""
//p+!
//l+p! ... goes this way
print ( str)
}
return str
}
print (reverse("!pleH"))