0
//MARK: - Reverse every other word

var sampleSentence = "Hey my name is Chris, what is yours?"

func reverseWordsInSentence(sentence: String) -> String {
    let allWords = sentence.components(separatedBy: " ")
    var newSentence = ""
    for word in allWords {
        if newSentence != "" {
            newSentence += " "
        }
        let reverseWord = String(word//.characters.reverse()) //Problem
        newSentence += word
    }
    
    return newSentence
}

I made a tutorial by "Lets Build That App" on YouTube but his video is from 2016. He wrote it like you can see above but the characters function of the String doesn't exist!

2
  • Use the for loop.reversed. Commented Feb 9, 2021 at 5:32
  • just remove the characters keyword newSentence += String(word.reversed()) Commented Feb 9, 2021 at 5:37

2 Answers 2

1

There is a few issues regarding the Swift version of that tutorial. First the character property from string has been removed. Second collection reverse method has been renamed to reversed. Third that logic is flawed because it would reverse the punctuations after the words. You can use string enumerateSubstrings in range, use byWords option, to get the range of the words in the sentence and reverse each word as follow:

func reverseWordsInSentence(sentence: String) -> String {
    var sentence = sentence
    sentence.enumerateSubstrings(in: sentence.startIndex..., options: .byWords) { _, range, _, _ in
        sentence.replaceSubrange(range, with: sentence[range].reversed())
    }
    return sentence
}

var sampleSentence = "Hey my name is Chris, what is yours?"

reverseWordsInSentence(sentence: sampleSentence)  // "yeH ym eman si sirhC, tahw si sruoy?"
Sign up to request clarification or add additional context in comments.

Comments

0

try this for reverse:

let reverseWord = String(word.reversed())
        newSentence += reverseWord

instead of:

let reverseWord = String(word)//.characters.reverse()) //Problem
        newSentence += word

output:

enter image description here

1 Comment

This solves the error but this would reverse the punctuation as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.