CeraMo69 CeraMo69 - 9 months ago 41
Swift Question

Swift - endIndex.predecessor()

Do these comments make any sense ?
Trying to figure out why it removes the character of my reversed given string, instead of the regular given string in this case.

import Foundation

extension String {
func reverseWords() -> String {
var result = ""

let words = self.componentsSeparatedByString(" ")
for thisWord in words.reverse() {
result += thisWord + " "

// Result is the words array ( contains self ) reversed with seperator " "


// So here i am checking self within result?, and am removing the last index
// of my currently reversed given string inside result?
// I do result in my intended last space removal with result.endIndex but i'm
// wondering what happens in this case with the self.endIndex :)

return result


var str = "This string contains a few elements"


self still refers to the original unreversed String.

The correct code would be:


You should never use a String index for another string. If you are indexing result, you shouldn't use an index from self.

With a simple string you won't seem a difference but if you start adding multi-byte characters, e.g. emojis, your application can crash.

For example, using result += thisWord + "