gpt4 book ai didi

swift - Swift 中日期类型的空值

转载 作者:行者123 更新时间:2023-11-30 10:57:43 24 4
gpt4 key购买 nike

我对 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,又名Double,表示自引用日期以来的秒数。然后,Date 的空初始值设定项将返回距该引用日期 0 秒的日期。这一切都取决于选择引用日期:

  • 现在:让 date1 = Date()
  • 1970 年 1 月 1 日上午 12:00:let date2 = Date(timeIntervalSince1970: 0)
  • 2001 年 1 月 1 日中午 12:00:let date3 = Date(timeIntervalSinceReferenceDate: 0)

如果您认为有意义,您可以选择某个日期作为引用。示例:Date.distantPastDate.distantFuture、...

现在,如果您希望变量具有特定类型,但没有值,则使用 optionals并将它们的值设置为nil:

var date4: Date? = nil

稍后,当您想实际使用该变量时,只需将其设置为非零值即可:

date4 = Date(timeInterval: -3600, since: Date())

要使用实际值,您必须使用可选绑定(bind)或类似方式将其解包。

关于swift - Swift 中日期类型的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53757375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com