我编写了一个TimeInterval
的扩展,它返回格式为"h m S"的字符串.例如,5小时33分15秒将被写为"5小时33分15秒".代码是这样的:
extension TimeInterval {
init(hours: Int, minutes: Int, seconds: Int) {
self = Double(hours * 3600 + minutes * 60 + seconds)
}
func toString() -> String {
let totalSeconds = Int(self)
let hours = totalSeconds / 3600
let minutes = (totalSeconds % 3600) / 60
let seconds = totalSeconds % 60
if hours >= 1 {
return "\(hours)h \(minutes)m"
} else if minutes >= 1 {
return "\(minutes)m \(seconds)s"
} else {
return "\(seconds)s"
}
}
}
我想用苹果的Duration.TimeFormatStyle
时尚来实现同样的功能.例如,我可以执行以下操作:
let style = Duration.TimeFormatStyle(pattern: .hourMinuteSecond)
var formattedTime = Duration.seconds(someInterval).formatted(style)
我认为这是比编写一个toString()
函数作为TimeInterval
的扩展更好的做法,但我不确定如何创建这种样式.任何指导都是很棒的.