krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Speech/SpokenText.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDay/Speech/SpokenText.swift history · blame · raw

31 lines · 955 bytes

2 symbols in this file
 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}