DayByDay/Speech/SpokenText.swift
31 lines · 955 bytes
1//
2// SpokenText.swift
3// DayByDay
4//
5
6import Foundation
7
8/// Splits spoken text into sentences, the unit voice clips are recorded in.
9nonisolated enum SpokenText {
10 /// A sentence ends at ".", "!" or "?" followed by a space or the end.
11 static func sentences(_ text: String) -> [String] {
12 var result: [String] = []
13 var current = ""
14 let chars = Array(text)
15 for (i, c) in chars.enumerated() {
16 current.append(c)
17 let atBreak = ".!?".contains(c) && (i + 1 == chars.count || chars[i + 1] == " ")
18 if atBreak {
19 append(current, to: &result)
20 current = ""
21 }
22 }
23 append(current, to: &result)
24 return result
25 }
26
27 private static func append(_ sentence: String, to result: inout [String]) {
28 let trimmed = sentence.trimmingCharacters(in: .whitespaces)
29 if !trimmed.isEmpty { result.append(trimmed) }
30 }
31}