String+GrammarCorrections.swift 636 B

123456789101112131415161718192021
  1. import Foundation
  2. extension String {
  3. func applyingGrammarCorrections(_ issues: [GrammarIssue]) -> String {
  4. guard !issues.isEmpty else { return self }
  5. var result = self
  6. var replacements: [(Range<String.Index>, String)] = []
  7. for issue in issues {
  8. guard let range = result.range(of: issue.original) else { continue }
  9. replacements.append((range, issue.suggestion))
  10. }
  11. for (range, suggestion) in replacements.sorted(by: { $0.0.lowerBound > $1.0.lowerBound }) {
  12. result.replaceSubrange(range, with: suggestion)
  13. }
  14. return result
  15. }
  16. }