Last active
May 8, 2018 01:38
-
-
Save chrisiona/af2200bc8790a46d7c577f6e3680587b to your computer and use it in GitHub Desktop.
Extend the SwiftyJSON module with a .date type (Swift3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SwiftyJsonExtension.swift | |
// | |
// Created by Chris Iona on 02/12/16. | |
// MIT License. | |
// | |
// Date extension for SwiftyJSON module | |
// https://github.com/SwiftyJSON/SwiftyJSON | |
// | |
// Assumes that you already have SwityJSON installed and available | |
// | |
import Foundation | |
import SwiftyJSON | |
extension JSON { | |
public var date: Date? { | |
get { | |
if let epoch = self.double { | |
// Convert epoch Interval (aka Double) to Date Object | |
return Date(timeIntervalSince1970: epoch) | |
} | |
return nil | |
} | |
set { | |
if let newValue = newValue { | |
// Store date object as epoch Interval (aka Double) | |
self.double = newValue.timeIntervalSince1970 | |
} else { | |
self.object = NSNull() | |
} | |
} | |
} | |
} | |
// | |
// Example usage in your Controller | |
// | |
/* | |
// Get the current point in time as Date (Struct) | |
let currentTime = Date() | |
// Create instance of JSON (SwiftyJson) | |
var json: JSON = [:] | |
// SET — becomes an Interval (aka Double) | |
json["currentTime"].date = currentTime | |
// GET — becomes an instance of Date | |
print( json["currentTime"].date! ) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment