WordLimit.swift 657 B

12345678910111213141516171819202122
  1. import Foundation
  2. enum WordLimit {
  3. static func message(maxWords: Int) -> String {
  4. "Maximum \(maxWords) words allowed."
  5. }
  6. static func apply(_ text: String, maxWords: Int) -> (text: String, exceeded: Bool) {
  7. guard text.wordCount > maxWords else { return (text, false) }
  8. return (text.truncated(toMaxWords: maxWords), true)
  9. }
  10. static func applyImported(
  11. _ text: String,
  12. maxWords: Int,
  13. setError: (String?) -> Void
  14. ) -> String {
  15. let (limited, exceeded) = apply(text, maxWords: maxWords)
  16. setError(exceeded ? message(maxWords: maxWords) : nil)
  17. return limited
  18. }
  19. }