只需添加
.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
}