如果你曾经写过类似这样的代码,那么这个微型库就是为你而生的
let interval: TimeInterval = 10 * 60
用来表示 10 分钟。
import Time
let tenMinutes = 10.minutes
let afterTenMinutes = Date() + 10.minutes
let tenMinutesAndSome = 10.minutes + 15.seconds
let tenMinutesInSeconds = 10.minutes.inSeconds
if 10.minutes > 500.seconds {
print("That's right")
}
Time 不仅仅是一堆 Double
转换函数。它的主要优势在于所有时间单位都是强类型的。例如
let tenMinutes = 10.minutes
这里 tenMinutes
实际上是 Interval<Minute>
类型(不要与 Foundation 的 TimeInterval
混淆)。有七个可用的时间单位,从纳秒到天
public extension Double {
var seconds: Interval<Second> {
return Interval<Second>(self)
}
var minutes: Interval<Minute> {
return Interval<Minute>(self)
}
var milliseconds: Interval<Millisecond> {
return Interval<Millisecond>(self)
}
var microseconds: Interval<Microsecond> {
return Interval<Microsecond>(self)
}
var nanoseconds: Interval<Nanosecond> {
return Interval<Nanosecond>(self)
}
var hours: Interval<Hour> {
return Interval<Hour>(self)
}
var days: Interval<Day> {
return Interval<Day>(self)
}
}
你可以对时间间隔执行所有基本的算术运算,即使是不同单位的时间间隔
let interval = 10.minutes + 15.seconds - 3.minutes + 2.hours // Interval<Minute>
let doubled = interval * 2
let seconds = 10.seconds + 3.minutes // Interval<Second>
你也可以在 Date
上使用这些操作
let oneHourAfter = Date() + 1.hours
时间间隔很容易转换
let twoMinutesInSeconds = 2.minutes.inSeconds // Interval<Second>
如果需要,你还可以将时间间隔转换为 Foundation 的 TimeInterval
let timeInterval = 5.minutes.timeInterval
你也可以使用 converted(to:)
方法
let fiveSecondsInHours = 5.seconds.converted(to: Hour.self) // Interval<Hour>
// or
let fiveSecondsInHours: Interval<Hour> = 5.seconds.converted()
虽然,在我看来,你很少需要这样做。
你也可以比较不同的时间单位
50.minutes < 1.hour
如果由于某种原因,你需要创建你自己的时间单位,那非常容易
public enum Week: TimeUnit {
public static var toTimeIntervalRatio: Double {
return 604800
}
}
现在你可以像使用任何其他时间单位一样使用它
let fiveWeeks = Interval<Week>(5)
为了方便起见,不要忘记编写那些方便的扩展
public enum Week: TimeUnit {
public static var toTimeIntervalRatio: Double {
return 604800
}
}
extension Interval {
public var inWeeks: Interval<Week> {
return converted()
}
}
extension Double {
public var weeks: Interval<Week> {
return Interval<Week>(self)
}
}
extension Int {
public var weeks: Interval<Week> {
return Interval<Week>(Double(self))
}
}
还有
let conversionRate = Hour.conversionRate(to: Second.self) // 3600.0
DispatchQueue.main.asyncAfter(after: 5.seconds) {
// do stuff
}
从 Xcode 11 开始,Time 仅通过 Swift Package Manager 正式提供。
在 Xcode 11 或更高版本中,在你的项目中,选择:File > Swift Packages > Add Package Dependency
在搜索栏中输入
https://github.com/dreymonde/Time
然后继续安装。
如果你在 Swift Packages 面板中找不到任何内容,可能是因为你还没有添加你的 github 帐户。你可以在 Xcode 的 Preferences 面板的 Accounts 部分中执行此操作。
对于基于命令行的应用程序,你可以直接将此添加到你的 Package.swift 文件中
dependencies: [
.package(url: "https://github.com/dreymonde/Time", from: "1.1.0"),
]
当然,你始终可以选择复制粘贴代码 - Time 只有两个文件,所以请随意。
支持 Carthage 和 Cocoapods 的最新 Time 版本是 1.0.1。Carthage 和 Cocoapods 将不再被正式支持。
Carthage
github "dreymonde/Time" ~> 1.0.1
Cocoapods
pod 'TimeIntervals', '~> 1.0.1'