I try to reverse sring and seems like i have some succes in this case:
let sampleSentence = "I like to learn Swift"
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
}
But I'm trying to go further and make sure that the reverse of the line does not affect the numbers for example:
let sampleSentence = "Test 1, I like to learn Swift 24/7"
now i have result:
print(reverseWordsInSentence(sentence: sampleSentence)) // 1tseT, I ekil ot nrael tfiwS 42/7
my goal is to achieve results:
print(reverseWordsInSentence(sentence: sampleSentence)) // tseT1, I ekil ot nrael tfiwS 24/7
I will be glad to any hints!
CodePudding user response:
You can add a check inside the closure and just return if the substring contains all numbers
guard let string = string, !string.allSatisfy(\.isNumber) else {
return
}
Full code
func reverseWordsInSentence(sentence: String) -> String {
var sentence = sentence
sentence.enumerateSubstrings(in: sentence.startIndex..., options: .byWords) { string, range, _, _ in
guard let string = string, !string.allSatisfy(\.isNumber) else {
return
}
sentence.replaceSubrange(range, with: sentence[range].reversed())
}
return sentence
}