Search code examples
swiftcustomstringconvertible

Swift equivalent of Haskell Show


What is the Swift equivalent of Haskell Show to print values inside Enumerations with cases? I have read Show is pretty similar to the Java toString() method and that the Swift CustomStringConvertible maybe a good option.

For example, using print on a Fraction instance would display:

> Fraction(numerator: 1, denominator: 2)

Rather than printing the entire case, I would like to print only the numbers with a slash in between. For example "1/2".

My current code is the following:

enum MyNum: Equatable {
  case Fraction(numerator: Int, denominator: Int)
  case Mixed(whole: Int, numerator: Int, denominator: Int)
}

extension MyNum: CustomStringConvertible {
  var description: String {
    return "(\(Fraction.numerator) / \(Fraction.denominator))"
  }
}

var testFraction= MyNum.Fraction(numerator: 1, denominator: 2)
print(testFraction)

Solution

  • You need to use a switch statement in description as well and read the associated values

    extension MyNum: CustomStringConvertible {
    var description: String {
      switch self {
        case .Fraction(let n, let d):
        return "\(n) / \(d)"
        case .Mixed(let w, let n, let d):
        return "\(w) \(n) / \(d)"
      }
    }
    

    Note that in swift enum items should start with a lowercase letter so it should be fraction and mixed