Swift 中日期类型的空值
Empty value for Date type in Swift
我对 swift 很陌生。
如何为 Swift 中的 Date
类型设置空值以便在声明中使用?
喜欢:
var string: String = ""
对于 String
类型
var integer: Int = 0
对于 Int
类型。
谢谢。
来自documentation :
A Date value encapsulate a single point in time, independent of any
particular calendrical system or time zone. Date values represent a
time interval relative to an absolute reference date.
换句话说,日期不过是 TimeInterval
、A.K.A 和 Double
表示自参考日期以来的秒数。然后,Date
的空初始值设定项将是 returns 距该参考日期 0 秒的日期。这一切都归结为选择参考日期:
- 现在:
let date1 = Date()
- 1970 年 1 月 1 日 12:00 上午:
let date2 = Date(timeIntervalSince1970: 0)
- 2001 年 1 月 1 日 12:00 上午:
let date3 = Date(timeIntervalSinceReferenceDate: 0)
如果您觉得合适,您可以选择某个日期作为参考。示例:Date.distantPast
、Date.distantFuture
、...
现在,如果您希望变量具有特定类型但没有值,请使用 optionals 并将它们的值设置为 nil
:
var date4: Date? = nil
稍后,当你想实际使用变量时,只需将其设置为非零值即可:
date4 = Date(timeInterval: -3600, since: Date())
要使用实际值,您必须使用可选绑定或类似方法将其解包。
我对 swift 很陌生。
如何为 Swift 中的 Date
类型设置空值以便在声明中使用?
喜欢:
var string: String = ""
对于 String
类型
var integer: Int = 0
对于 Int
类型。
谢谢。
来自documentation :
A Date value encapsulate a single point in time, independent of any particular calendrical system or time zone. Date values represent a time interval relative to an absolute reference date.
换句话说,日期不过是 TimeInterval
、A.K.A 和 Double
表示自参考日期以来的秒数。然后,Date
的空初始值设定项将是 returns 距该参考日期 0 秒的日期。这一切都归结为选择参考日期:
- 现在:
let date1 = Date()
- 1970 年 1 月 1 日 12:00 上午:
let date2 = Date(timeIntervalSince1970: 0)
- 2001 年 1 月 1 日 12:00 上午:
let date3 = Date(timeIntervalSinceReferenceDate: 0)
如果您觉得合适,您可以选择某个日期作为参考。示例:Date.distantPast
、Date.distantFuture
、...
现在,如果您希望变量具有特定类型但没有值,请使用 optionals 并将它们的值设置为 nil
:
var date4: Date? = nil
稍后,当你想实际使用变量时,只需将其设置为非零值即可:
date4 = Date(timeInterval: -3600, since: Date())
要使用实际值,您必须使用可选绑定或类似方法将其解包。