如何让DateComponentsFormatter.string(from:)结果的第一个字大写?

How to make the first word of DateComponentsFormatter.string(from:)'s result capitalised?

在我的 iOS 项目中,我有一个函数可以将整数值转换为带有 "seconds" 后缀的字符串:

func secondsToString(_ seconds: Int) -> String {    
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.allowedUnits = [.second]
    return formatter.string(from: DateComponents(second: seconds)) ?? ""
}

我是这样称呼它的:

print(secondsToString(10)) // Output is "10 seconds"
print(secondsToString(1)) // Output is "1 second"

但是我需要将 secondsToString 结果的第一个单词大写,例如:

print(secondsToString(10)) // Output is "10 Seconds"
print(secondsToString(1)) // Output is "1 Second"

我该如何解决这个问题?我应该更改 DateComponentsFormatter 中的一些 属性 吗?

只需在格式化字符串的末尾添加 .capitalized

func secondsToString(_ seconds: Int) -> String {
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.allowedUnits = [.second]
    return formatter.string(from: DateComponents(second: seconds))?.capitalized ?? ""
}

注意:此解决方案将从该方法返回的所有单词大写。对于您的用例,这应该足够好,因为即使您添加更多时间单位,如果我将一个时间单位大写,我更愿意将所有时间单位都大写。


因此,如果您要以某种方式更改结果并且只想将第一个单词大写,您可以尝试这样做:(第一个单词表示第一个包含字母的单词)

func secondsToString(_ seconds: Int) -> String {
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.allowedUnits = [.second, .hour, .day]
    let string = formatter.string(from: DateComponents(second: seconds)) ?? ""
    var substrings = string.components(separatedBy: " ")
    // Using for...each would make the iterating element a constant and hence i would have to find the index and replace it using the index
    for i in 0...substrings.count {     
        if let firstCharacter = substrings[i].unicodeScalars.first, CharacterSet.letters.contains(firstCharacter) {
            substrings[i] = substrings[i].capitalized
            break
        }
    }
    let finalString = substrings.joined(separator: " ")
    return finalString
}