user14730646
user14730646

Reputation:

How to write a Swift String Characters.reverse function in 2021

//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!

Upvotes: 0

Views: 429

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236370

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?"

Upvotes: 1

hessam
hessam

Reputation: 432

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

Upvotes: 0

Related Questions