A type safe swift ResultBuilder DSL for structured directories
2.2 kB
66 lines
1extension Conversion {
2 /// A conversion from a string to a lossless string-convertible type.
3 ///
4 /// See ``lossless(_:)-swift.method`` for a fluent version of this interface that transforms an
5 /// existing conversion.
6 ///
7 /// - Parameter type: A type that conforms to `LosslessStringConvertible`.
8 /// - Returns: A conversion from a string to the given type.
9 @inlinable
10 public static func lossless<NewOutput>(
11 _ type: NewOutput.Type
12 ) -> Self where Self == Conversions.FromLosslessString<NewOutput> {
13 .init()
14 }
15
16 /// Transforms this conversion to a string into a conversion to the given lossless
17 /// string-convertible type.
18 ///
19 /// A fluent version of ``Conversion/lossless(_:)-swift.type.method``. Equivalent to calling
20 /// ``map(_:)`` with ``Conversion/lossless(_:)-swift.type.method``:
21 ///
22 /// ```swift
23 /// stringConversion.lossless(NewOutput.self)
24 /// // =
25 /// stringConversion.map(.lossless(NewOutput.self))
26 /// ```
27 ///
28 /// - Parameter type: A type that conforms to `LosslessStringConvertible`.
29 /// - Returns: A conversion from a string to the given type.
30 @inlinable
31 public func lossless<NewOutput>(
32 _ type: NewOutput.Type
33 ) -> Conversions.Map<Self, Conversions.FromLosslessString<NewOutput>> {
34 self.map(.lossless(NewOutput.self))
35 }
36}
37
38extension Conversions {
39 /// A conversion from a string to a lossless string-convertible type.
40 ///
41 /// You will not typically need to interact with this type directly. Instead you will usually use
42 /// the ``Conversion/lossless(_:)-swift.type.method`` operation, which constructs this type.
43 public struct FromLosslessString<Output: LosslessStringConvertible>: Conversion {
44 @usableFromInline
45 init() {}
46
47 @inlinable
48 public func apply(_ input: String) throws -> Output {
49 guard let output = Output(input)
50 else {
51 throw ConvertingError(
52 """
53 lossless: Failed to convert \(input.debugDescription) to \(Output.self).
54 """
55 )
56 }
57
58 return output
59 }
60
61 @inlinable
62 public func unapply(_ output: Output) -> String {
63 output.description
64 }
65 }
66}