简体   繁体   English

如何在 Swift 中将 NSDateComponents 转换为 DateComponents

[英]How to convert NSDateComponents to DateComponents in Swift

I want to conver NSDateComponents to DateComponents.我想将 NSDateComponents 转换为 DateComponents。 How can I do it in Swift without force casting.我如何在没有强制转换的情况下在 Swift 中做到这一点。

There is nothing to convert.没有什么可以转换的。 Just use DateComponents wherever you would previously have used NSDateComponents.只需在您以前使用 NSDateComponents 的地方使用DateComponents。

(You can in fact cast from one to the other using as , but you will never need to. Your code should contain no reference to NSDateComponents in Swift 3. You use DateComponents instead .) (你实际上可以从铸一方向另一方使用as ,但你永远不会需要。您的代码应该包含在斯威夫特3.您使用DateComponents反而没有提及NSDateComponents。)

As a addition to why the question is valid and and an example of why:作为该问题有效原因的补充以及原因的示例:

Not all APIs are yet converted to DateComponents.并非所有 API 都已转换为 DateComponents。 One example is the Contact framework where the instance property dates of the CNContact/CNMutableContact classes is declared as一个例子是 Contact 框架,其中 CNContact/CNMutableContact 类的实例属性dates被声明为

open var dates: [CNLabeledValue<NSDateComponents>]

Unfortunately there is no built-in way to convert between the two so if you want to avoid force casting you will have to set each property your self:不幸的是,没有内置的方法可以在两者之间进行转换,因此如果您想避免强制转换,则必须自行设置每个属性:

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

Be aware that it is not a 1:1 mapping of the properties of the two classes, you will have to look up the API if you want to do a complete mapping.请注意,这不是两个类的属性的 1:1 映射,如果要进行完整映射,则必须查找 API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM