【问题标题】:How to convert NSDateComponents to DateComponents in Swift如何在 Swift 中将 NSDateComponents 转换为 DateComponents
【发布时间】:2016-09-27 19:32:20
【问题描述】:

我想将 NSDateComponents 转换为 DateComponents。我如何在 Swift 中做到这一点而无需强制转换。

【问题讨论】:

  • 不知道为什么这个问题被关闭或否决。很高兴知道原因,因为这是一个有效的问题,其答案在 Apples API Docs 中是未知的。没有可用于将 NSDateComponents 转换为 DateComponents 的公共方法,我不想强​​制转换它。
  • @EricAya @matt 的回答并不完全正确。我已经在一个项目中尝试过了,它迫使我使用 NSDateComponent 投射 as DateComponent
  • 错误:无法将类型“DateComponents”的值转换为指定类型“NSDateComponents”让 x: NSDateComponents = DateComponents() ^~~~~~~~~~~~~~~~ as NSDateComponents
  • @EricAya 好的,所以我的问题的答案是没有要转换的公共 API,但我们只需要替换代码中的用法。仍然不确定为什么这个问题被否决,因为它是一个有效的问题,下面有不同的答案
  • 另外,我注意到这里大约有一半的讨论是关于DateComponent->NSDateComponent,但问题恰恰相反。

标签: swift nsdatecomponents


【解决方案1】:

没有什么可以转换的。只需使用 DateComponents,只要你以前使用过 NSDateComponents。

(实际上,您可以使用as 从一个转换到另一个,但您永远不需要。您的代码应该包含 no 对 Swift 3 中 NSDateComponents 的引用。您使用 DateComponents 而不是。)

【讨论】:

  • 如果 API 使用NSDateComponents,你几乎别无选择。即使您使用 DateComponents 编写所有代码,也无法 100% 避免它。
【解决方案2】:

作为问题有效原因的补充以及为什么的示例:

并非所有 API 都已转换为 DateComponents。一个例子是 Contact 框架,其中 CNContact/CNMutableContact 类的实例属性dates 声明为

open var dates: [CNLabeledValue<NSDateComponents>]

不幸的是,没有内置的方法可以在两者之间进行转换,所以如果你想避免强制转换,你必须自己设置每个属性:

nsDateComponents.day = dateComponents.day
nsDateComponents.month = dateComponents.month
// etc ...

请注意,这不是两个类的属性的 1:1 映射,如果要进行完整映射,则必须查找 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2019-04-23
    • 2014-10-23
    相关资源
    最近更新 更多