Last active
July 21, 2023 14:21
-
-
Save krzyzanowskim/82baa9bb11567ab8c7c8e4a631fe4647 to your computer and use it in GitHub Desktop.
ReversibleFormatStyle - like FormatStyle but reversible, more like Formatter
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
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