带排除规则的反向字符串

Reverse string with exclusion rules

我尝试反转 sring,似乎我在这种情况下取​​得了一些成功:

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
}

但我正在尝试更进一步,确保线条的反转不会影响数字 例如:

let sampleSentence = "Test 1, I like to learn Swift 24/7"

现在我有结果:

print(reverseWordsInSentence(sentence: sampleSentence)) // 1tseT, I ekil ot nrael tfiwS 42/7

我的目标是实现结果:

print(reverseWordsInSentence(sentence: sampleSentence)) // tseT1, I ekil ot nrael tfiwS 24/7

我会很高兴得到任何提示!

您可以在闭包内添加一个检查,如果子字符串包含所有数字

,则 return
guard let string = string, !string.allSatisfy(\.isNumber) else  {
    return
}

完整代码

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
}