Decodable multiple DateDecodingStrategies

Decodable multiple DateDecodingStrategies

Content Index :

Decodable multiple DateDecodingStrategies
Tag : ios , By : Search Classroom
Date : November 15 2020, 03:01 PM

it fixes the issue You can use the DateDecodingStrategy.custom option for that. A short example:
let shortFormatter = DateFormatter()
let longFormatter = DateFormatter()
shortFormatter.dateFormat = "yyyy-MM-dd"
longFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

func customDateFormatter(_ decoder: Decoder) throws -> Date {
    let dateString = try decoder.singleValueContainer().decode(String.self)
    let dateKey = decoder.codingPath.last as! Movie.CodingKeys
    switch dateKey {
    case .shortDate :
        return shortFormatter.date(from: dateString)!
    case .longDate :
        return longFormatter.date(from: dateString)!
        fatalError("Unexpected date coding key: \(dateKey)")
let json =
    "name": "A Clockwork Orange",
    "short_date": "2017-10-10",
    "long_date": "2017-10-10 12:21:02"
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom(customDateFormatter)
let movie = try! decoder.decode(Movie.self, from: json)

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Swift 4 Decodable multiple containers

Tag : json , By : Robert Daniel Pickar
Date : March 29 2020, 07:55 AM
help you fix your problem Please read the JSON.
Any opening { is quasi a separator. The indentation of the JSON indicates also the hierarchy.
struct Root : Decodable {
    let graphql : Graph

    // to access the `Media` object declare a lazy instantiated property

    lazy var media : Media = {
        return graphql.shortcode_media

struct Graph : Decodable {
    let shortcode_media : Media

struct Media : Decodable {
    let id: String
    let shortcode : String
let jsonString = """
    "graphql": {
        "shortcode_media": {
            "id": "1657677004214306744",
            "shortcode": "BcBQHPchwe4"
do {       
    let data = Data(jsonString.utf8) 
    var result = try decoder.decode(Root.self, from: data)
} catch {
    print("error: ", error)

Fatal error: Dictionary<String, Any> does not conform to Decodable because Any does not conform to Decodable

Tag : ios , By : ussballantyne
Date : March 29 2020, 07:55 AM
I hope this helps . Maybe you are misunderstanding how Codable works. It's based on concrete types. Any is not supported.
In your case you might create a struct like
struct Something: Decodable {
    let success : Bool
    let lastId : Int?
    let hasMore: Bool
    let foundEndpoint: URL
    let error: String?
func loadLocalJSON() {
    let url = Bundle.main.url(forResource: "localJSON", withExtension: "json")!
    let data  = try! Data(contentsOf: url)
    let colors = try! JSONDecoder().decode(Something.self, from: data)

getting decodable error when trying to use decodable struct in another as array

Tag : swift , By : KingGuppy
Date : March 29 2020, 07:55 AM
I hope this helps . I'm getting in decodable error: does not conform to Decodable ... , It should be like this,
struct Root2 : Decodable {
    let services : [Services]
    let nationalities : [Nationalities]
    let packages : [Packages]

Swift Decodable fails for a class derived from a decodable compliant class (JSONDecoder is used for decoding)

Tag : json , By : Andrew Bailey
Date : March 29 2020, 07:55 AM
will be helpful for those in need You need to implement init(from decoder: Decoder) in the subclass and call the superclass init although you don't need to implement it for the superclass
init for CardListResponse, notice the call to super.init
required public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    cards = try container.decode([DebitCard].self, forKey: .cards)
    activeCardId = try container.decode(Int.self, forKey: .activeCardId)
    try super.init(from: decoder)
public class CardListResponse: Decodable {
    public var cards: [DebitCard]?
    public var activeCardId: Int?
    public var details: [CodeAndDetails]

    private enum CodingKeys: String, CodingKey {
        case cards = "row"
        case activeCardId = "CurrentActiveId"
        case details = "Success"

Array of Decodable type is not decodable

Tag : swift , By : Feroz
Date : March 29 2020, 07:55 AM
Hope this helps If we have a type Foo: Decodable how can we make Array decodable? , Just use this:
let res = JSONDecoder().decode([Foo].self, data)
Related Posts Related QUESTIONS :
  • How can I prevent the stopwatch from resetting after pause
  • Cannot convert value of type '() -> _' to specified type '[UIViewController]'
  • How to make a reference to a uid stored in Firestore?
  • How do you initialize/use UITableViewCells with CellStyle = .value1 programmatically?
  • How to know if Apple has received our appeal/how long does it take Apple to respond?
  • Select new item added to SwiftUI List
  • What is the correct length: argument to provide to NSRange for NSRegularExpression using a (Swift) String?
  • I am trying to delete data from database, but sometime data is deleted and sometime data is not deleted
  • How to get slider value with subview rotation angle
  • Can't pass custom UINavigationBar / UIToolbar to UINavigationController because they don't conform to AnyClass
  • Grab SELECTED text on UITextView
  • Clever ways to better test GPS code using only the iPhone simulator?
  • Remove app before simulator or device is lunched from Xcode
  • Auto Layout constraints for container view inside UITableView header broken for different devices
  • iPhone restarts after API call
  • What is the shortcut / How do I create function after writing it's usage in Xcode
  • Convert apple time stamp to Unix time
  • No podspec found for `React-fishhook`
  • How to test touch dialog and perform real in-app purchase?
  • Compiling Metal shaders from source on iOS 13 Simulator gives PCH error
  • conan error:I need to cross build packages for os:iOS with my Macos, but when the first package was done, it broke my cp
  • Update calendar 'start of week' from phones system calendar
  • Xcode is showing some warnings
  • How to remove the default Navigation Bar space in SwiftUI NavigiationView
  • Having trouble integrating multiple pickerviews in the same view
  • SCNNode not in SCNView hierarchy, still showing & getting touches & physics
  • How can I open my SwiftUI app and perform a function using NSUseractivity from within Siri Intent Extension?
  • NSCoding decodeObject always nil
  • Passing data in a segmented Controller?
  • Facing issue in Siri Integration with custom intents
  • ARKit3 Hardware Requirement Clarification
  • ARKit3 How to use TrueDepth camera for face tracking and face meshes of other people?
  • How to discriminate while decoding using Codable Protocol in Swift?
  • 'IPA processing failed' while distributing build in Xcode Beta
  • How to debug a crash which happened when come back from background
  • Synchronising old data with NSPersistentCloudKitContainer
  • iOS app opened from web app with url redirects to Appstore
  • How to change the color of seperator in tableView?
  • Is there a better way to watch for a key-value change?
  • How to make UIBezierPath to fill from the center
  • Why on Xcode 11, UICollectionViewCell changes size as soon as you scroll (I already set size in sizeForItem AtIndexPath:
  • How to scan non LE devices using Swift?
  • Unable to infer closure type in the current context in SwiftUI
  • What is the best way to write common code and use it entire project
  • UISegmentedControl inside UIStackView, segments text not centered - iOS 13
  • Swift & ObjC bridge - cannot find protocol declaration for "WKNavigationDelegate"
  • SwiftUI How to push to next screen when tapping on Button
  • 'NSApp' is unavailable in UIKit for Mac: How to embed Mac only framework in iOS app on macOS?
  • UserDefaults Binding with Toggle in SwiftUI
  • How to create a color with an alpha value using SwiftUI?
  • SwiftUI creates destination views before the user navigates to them
  • Streaming video from https with AVPlayer causes initial delay
  • Tap Action not working when Color is clear SwiftUI
  • SwiftUI NavigationButton: How to navigate to different destinations
  • Supported default light/dark mode colors for Color vs UIColor
  • XCUITest wait for a cell with a specific static text inside it
  • Not able to enable Development mode on iOS 13
  • How to hide the home indicator with SwiftUI?
  • How to write if condition with using label text (Int) values
  • Swift Cannot use instance member within property initializer
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com