ios - 如何制作DateComponentsFormatter.string的第一个字(来自:)'s result capitalised?

标签 ios swift foundation dateformatter

在我的 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
}

关于ios - 如何制作DateComponentsFormatter.string的第一个字(来自:)'s result capitalised?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741281/

相关文章:

swift - NSPopover OS X 应用程序

objective-c - Objective C - 使用相同实例变量的两个合成属性?

objective-c - 将 CFIndex 转换为 NSUInteger?

swift - 在命令行工具上使用 Swift URLSession 示例代码

ios - 无法在 swift 中调用 post 请求中的错误

ios - 从 Parse 中的指针列获取数据(iOS)

ios - 为什么 CGFloat 会补足有效数字?

ios - 在核心数据中保存一对多关系,但关闭模拟器后关系中只有一项。控制台 Swift 中的错误

swift - 为什么我的 AVCapturePhotoOutput 文件输出这么大?

ios - UIImage 数组到 PDF 转换内存泄漏