Uploaded image for project: 'Swift'
  1. Swift
  2. SR-2062

Optionals do not conform to CustomStringConvertible

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Standard Library
    • Labels:
      None

      Description

      Optionals do not currently conform to CustomStringConvertible so their representations do not use the preferred representation of the wrapped value:

      let amount: Float? = 3.8
      print(amount) // prints Optional(3.79999995)
      print(amount!) // prints 3.8
      

      Conforming Optional to CustomStringConvertible pricks up the value's preferred output style:

      extension Optional : CustomStringConvertible {
          /// A textual representation of this instance, suitable for printing.
          public var description: String {
              switch self {
              case .some(let value):
                  var result = "Optional("
                  print(value, terminator: "", to: &result)
                  result += ")"
                  return result
              case .none:
                  return "nil"
              }
          }
      }

      When added, the output is

      let amount: Float? = 3.8
      print(amount) // prints Optional(3.8)
      print(amount!) // prints 3.8
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              erica erica sadun
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

                Dates

                Created:
                Updated: