// A machine word, read out as a person would say it. // // A value the app has no label for — a kind a newer build added, a document // type an older one wrote, the last part of an app's id — is never drawn as it // is stored. It is split into words at underscores, hyphens, dots, spaces and // lower-to-upper case changes, and written as a sentence: `PAY_SLIP` reads // "Pay slip", `news_edition` "News edition", `SomeDialler` "Some dialler". // A short all-capitals word inside mixed case is an initialism ("ID") and // keeps its case; a value written wholly in capitals is not shouting initials, // so it is read in lower case. import Foundation public enum PlainWords { /// The identifier as a sentence; nil when it holds no word at all. public static func sentence(_ identifier: String) -> String? { var words: [String] = [] var current = "" var previous: Character? for character in identifier { if character == "_" || character == "-" || character == "." || character.isWhitespace { if !current.isEmpty { words.append(current) } current = "" } else { if let previous, previous.isLowercase, character.isUppercase, !current.isEmpty { words.append(current) current = "" } current.append(character) } previous = character } if !current.isEmpty { words.append(current) } guard !words.isEmpty else { return nil } let letters = identifier.filter(\.isLetter) let shouted = !letters.isEmpty && letters == letters.uppercased() let written = words.enumerated().map { index, word -> String in let initialism = !shouted && word.count > 1 && word == word.uppercased() && word.contains(where: \.isLetter) if initialism { return word } let lower = word.lowercased() return index == 0 ? lower.prefix(1).uppercased() + lower.dropFirst() : lower } return written.joined(separator: " ") } }