قالب وردپرس درنا توس
Home / IOS Development / # 316: Codable Dates 📠 – Little Bites of Cocoa

# 316: Codable Dates 📠 – Little Bites of Cocoa



Subjects

Topics

In Bite 315 we began to look at the new Codable protocol in Swift 4 . Today, we learn how to work with Date types when you encode and decode. Let's go diving.

[19659000] [19659000] [19659000] [19659000]
: : [19659000] [19659000]: [19659000][19659000] createdAt : Date
}

Then we will make one and code it into JSON to see

  la [1
9659022]
]:

   

  

  

   

 ]    gives    =    JSONEncoder  () 

  if    With    data [19659025] =    try     ] gives .  Code  (  Ship )   {
    Press  (  String  (  data :    data  ]        utf8 )  [19659015]) 
} 

This prints:

  {
    "Name" :   "Skyhopper"  
    "createdAt" :   524735194.61138701  
} 

There is much more than meeting the eye here though. The JSONEncoder we created has some incredibly useful features on it.

The one we wish is .dateEncodingStrategy . Yes, there is a swift enum with all kinds of goodies inside. Let's check them out.

We have already seen the default option, called .deferredToDate . Another great is .iso8601 :

  {[19659073] "name" :   "Skyhopper"  
    "createdAt" : [19659068] "2017-08-18T07: 50: 53Z"  
] 

Delicious to see what is built into the system in such a way.

Decoder also has a similar feature.

We've all had to decode a crazy day format from an HTTP API before.

We must only use the .formatted (DateFormatter) value of our property JSONDecoder s .dateDecodingStrategy property. [19659000] We give it this JSON to decode:

  {
    "name" :   "Skyhopper"  
    "createdAt"  :   "Friday, Aug 18, 2017"  
] 

Then we will set up the decoder and formatting:

  la    decoder    =    JSONDecoder  () 

  la    format   ] [19659015] DateFormatter  () 
  format .   dateformat    =    "EEEE, MMM d, yyyy" 

  decoder .   dateDecodingStrategy    =  .   formatted  (  formatting ) 
  la    data    =    jsonString .   data [19659015] (  with .      utf8 ).  

  sample     decoder    decode  (]       from :    data ) 

which decodes to struct as expected: 19659162] spacecraft (
name: "skyhopper"
created: 2017-08-18 05:00:00 +0000
)

Neat!

That's all for now. Happy coding!


Source link