I want to conver NSDateComponents to DateComponents. How can I do it in Swift without force casting.
-
2Not sure why this question is being closed or downvoted. Would be good to know the reason as this is a valid question whose answer is not known in the Apples API Docs. There is no public method available to convert NSDateComponents to DateComponents and I do not want to just force cast it. – Encore PTL Sep 29 '16 at 16:44
-
@EricAya @matt's answer is not entirely true. I have tried this out in a project and it forced me to cast `NSDateComponent` I had using `as DateComponent` – Encore PTL Sep 29 '16 at 16:54
-
error: cannot convert value of type 'DateComponents' to specified type 'NSDateComponents' let x: NSDateComponents = DateComponents() ^~~~~~~~~~~~~~~~ as NSDateComponents – Encore PTL Sep 29 '16 at 16:58
-
@EricAya OK so the answer to my question is there is no public API to convert but we just have to replace the usage in our code. Still not sure why this question was downvoted as it is a valid question with differing answers below – Encore PTL Sep 29 '16 at 17:06
-
Also, I noticed about half the discussion here is about `DateComponent`->`NSDateComponent`, but the question is about the opposite. – benc Jan 20 '22 at 06:00
2 Answers
There is nothing to convert. Just use DateComponents wherever you would previously have used NSDateComponents.
(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.)

- 515,959
- 87
- 875
- 1,141
-
If the API uses `NSDateComponents`, you pretty much don't have a choice. Even if you write all your code w/ `DateComponents`, you can't avoid it 100%. – benc Jan 20 '22 at 05:55
As a addition to why the question is valid and and an example of why:
Not all APIs are yet converted to DateComponents. One example is the Contact framework where the instance property dates
of the CNContact/CNMutableContact classes is declared as
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.

- 7
- 2