Skip to content

Instantly share code, notes, and snippets.

@NicholasTD07
Last active August 29, 2015 14:22
Show Gist options
  • Save NicholasTD07/67fb7a96b93d6ca828bf to your computer and use it in GitHub Desktop.
Save NicholasTD07/67fb7a96b93d6ca828bf to your computer and use it in GitHub Desktop.
Argo extension example
import Argo
let json = [
"urlString": "http://www.example.com",
"timestamp": 1433132865,
"date": "20150525",
"intString": "12345",
]
struct ExampleModel {
let urlFromString: NSURL
let dateFromTimeStamp: NSDate
let dateFromStringWithFormat: NSDate
let intFromString: Int
}
let model: ExampleModel? = decode(json)
extension ExampleModel: Decodable {
static func create(urlFromString: NSURL)(dateFromTimeStamp: NSDate)(dateFromStringWithFormat: NSDate)(intFromString: Int) -> ExampleModel {
return ExampleModel(urlFromString: urlFromString, dateFromTimeStamp: dateFromTimeStamp, dateFromStringWithFormat: dateFromStringWithFormat, intFromString: intFromString)
}
static func decode(j: JSON) -> Decoded<ExampleModel> {
return ExampleModel.create
<^> j <| "urlString"
<*> (j <| "timestamp" >>- toNSDate)
<*> (j <| "date" >>- toNSDate("yyyyMMdd"))
<*> (j <| "intString" >>- toInt)
// use parentheses to make sure the order of execution
// <^> j <| "urlString"
// <*> ((j <| "timestamp") >>- toNSDate)
// <*> ((j <| "date") >>- toNSDate("yyyyMMdd"))
// <*> ((j <| "intString") >>- toInt)
}
}
public func toNSDate(format: String)(dateString: String) -> Decoded<NSDate> {
return .fromOptional(NSDate.dateFromString(dateString, format: format))
}
public func toNSDate(#fromTimeStamp: NSTimeInterval) -> Decoded<NSDate> {
return pure(NSDate(timeIntervalSince1970: fromTimeStamp))
}
public func toInt(string: String) -> Decoded<Int> {
return .fromOptional(string.toInt())
}
extension NSURL: Decodable {
public static func decode(j: JSON) -> Decoded<NSURL> {
switch(j) {
case let .String(s): return .fromOptional(NSURL(string: s))
default: return .TypeMismatch("\(j) is not a NSURL.")
}
}
}
extension NSDate {
public class func dateFromString(string: String, format: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.dateFromString(string)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment