Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active July 21, 2023 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/82baa9bb11567ab8c7c8e4a631fe4647 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/82baa9bb11567ab8c7c8e4a631fe4647 to your computer and use it in GitHub Desktop.
ReversibleFormatStyle - like FormatStyle but reversible, more like Formatter
import Foundation
// like FormatStyle but reversible, more like Formatter
protocol ReversibleFormatStyle<FormatOutput>: FormatStyle {
func format(_ value: FormatOutput) -> FormatInput
}
// Implementation
struct ReversibleNumFormatStyle: ReversibleFormatStyle {
typealias FormatInput = Double
typealias FormatOutput = String
func format(_ value: Double) -> String {
value.formatted()
}
func format(_ value: String) -> Double {
Double(value) ?? 0
}
}
// Usage
let input: Double = 1.0
print("input : \(input) \(type(of: input))")
let formatStyle = ReversibleNumFormatStyle()
let output = formatStyle.format(input) as String
print("output: \(output) \(type(of: output))")
let revInput = formatStyle.format(output) as Double
print("revers: \(revInput) \(type(of: revInput))")
// ----------
// input : 1.0 Double
// output: 1 String
// revers: 1.0 Double
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment