Skip to content

Instantly share code, notes, and snippets.

@MattSHallatt
Created November 30, 2017 17:44
Show Gist options
  • Save MattSHallatt/ab84e0c594e5cb8a26b239689fbbe68d to your computer and use it in GitHub Desktop.
Save MattSHallatt/ab84e0c594e5cb8a26b239689fbbe68d to your computer and use it in GitHub Desktop.
Formatter
//
// Formatter.swift
// Formatter
//
// Created by Matthew Hallatt on 30/11/2017.
// Copyright © 2017 Gospelware. All rights reserved.
//
import Foundation
extension Formatter.DateFormat: RawRepresentable {
public typealias RawValue = DateFormatter
init?(rawValue: DateFormatter) {
switch rawValue {
case Formatter.DateFormat.timeFormatter:
self = .time
case Formatter.DateFormat.dateFormatter:
self = .date
default:
return nil
}
}
public var rawValue: DateFormatter {
switch self {
case .time:
return Formatter.DateFormat.timeFormatter
case .date:
return Formatter.DateFormat.dateFormatter
}
}
}
extension Formatter.TimeIntervalFormat: RawRepresentable {
public typealias RawValue = DateComponentsFormatter
init?(rawValue: DateComponentsFormatter) {
switch rawValue {
case Formatter.TimeIntervalFormat.durationFormatter:
self = .duration
default:
return nil
}
}
public var rawValue: DateComponentsFormatter {
switch self {
case .duration:
return Formatter.TimeIntervalFormat.durationFormatter
}
}
}
extension Formatter.NumberFormat: RawRepresentable {
public typealias RawValue = NumberFormatter
init?(rawValue: NumberFormatter) {
switch rawValue {
case Formatter.NumberFormat.decimalFormatter:
self = .decimal
case Formatter.NumberFormat.integerFormatter:
self = .integer
default:
return nil
}
}
public var rawValue: NumberFormatter {
switch self {
case .decimal:
return Formatter.NumberFormat.decimalFormatter
case .integer:
return Formatter.NumberFormat.integerFormatter
}
}
}
struct Formatter {
enum DateFormat {
static var timeFormatter = DateFormatter()
static var dateFormatter = DateFormatter()
case time
case date
}
enum TimeIntervalFormat {
static var durationFormatter = DateComponentsFormatter()
case duration
}
enum NumberFormat {
static var decimalFormatter = NumberFormatter()
static var integerFormatter = NumberFormatter()
case decimal
case integer
}
static func stringFrom(date: Date, withFormat format: DateFormat) -> String {
return format.rawValue.string(from: date)
}
static func stringFrom(timeInterval: TimeInterval, withFormat format: TimeIntervalFormat) -> String? {
return format.rawValue.string(from: timeInterval)
}
static func stringFrom(timeIntervalBetweenDate initialDate: Date, andDate finalDate: Date, withFormat format: TimeIntervalFormat) -> String? {
return format.rawValue.string(from: initialDate, to: finalDate)
}
static func stringFrom(number: NSNumber, withFormat format: NumberFormat) -> String? {
return format.rawValue.string(from: number)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment